从文件读取时 VBA ReadLine 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11051964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA ReadLine Error while reading from a file
提问by logan
I am using Excel 2003 & I have following code in my macro.
我正在使用 Excel 2003 & 我的宏中有以下代码。
Dim fs, a, retstring
Set fs = CreateObject("scripting.filesystemobject")
Set a = fs.OpenTextFile("C:\file.txt", ForReading, False)
Do While a.AtEndofStream <> True
retstring = a.ReadLine
Loop
a.Close
When I execute this, it shows
当我执行这个时,它显示
"Runtime Error:5"
Invalid Procedure Call or argument at OpenTextFile
“运行时错误:5”
OpenTextFile 中的过程调用或参数无效
回答by deusxmach1na
You must define the constant ForReading first. And you may as well define the constants ForWriting and ForAppending while you're at it.
您必须首先定义常量 ForReading。您也可以在使用时定义常量 ForWriting 和 ForAppending。
Dim fs, a, retstring
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile("C:\file.txt", ForReading, False)
Do While a.AtEndofStream <> True
retstring = a.readline
Loop
a.close
回答by Siddharth Rout
fso is considered slow. Here is a faster method to read a text file.
fso 被认为是缓慢的。这是读取文本文件的更快方法。
Sub Sample()
Dim MyData As String, strData() As String
Dim i as Long
'~~> Read the entire file in 1 go
Open "C:\MyFile.Txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
For i = LBound(strData) To UBound(strData)
Debug.Print strData(i)
Next
End Sub
回答by logan
It worked when i did like this.
当我这样做时它起作用了。
Dim fs, a, retstring
Set fs = CreateObject("scripting.filesystemobject")
Set a = fs.OpenTextFile("C:\Users8319\Desktop\file.txt", 1, False)
Do While a.AtEndofStream <> True
retstring = a.readline
Loop
a.Close
回答by zoltanh
I am using Excel 2007 and got the same problem with near the same code snippet. Enabling 'Microsoft Scripting Runtime' should solve it (Main menu >Tools > References), it worked for me.
我正在使用 Excel 2007 并且在接近相同的代码片段时遇到了同样的问题。启用“Microsoft Scripting Runtime”应该可以解决它(主菜单>工具>参考),它对我有用。