0

我正在使用 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

当我执行此操作时,它显示

“运行时错误:5”

OpenTextFile 中的过程调用或参数无效

4

4 回答 4

2

您必须首先定义常量 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
于 2012-06-15T14:32:24.600 回答
2

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
于 2012-06-15T16:27:07.417 回答
0

当我这样做时它起作用了。

    Dim fs, a, retstring
    Set fs = CreateObject("scripting.filesystemobject")
    Set a = fs.OpenTextFile("C:\Users\228319\Desktop\file.txt", 1, False)
    Do While a.AtEndofStream <> True
    retstring = a.readline
    Loop
    a.Close
于 2012-06-15T14:18:49.907 回答
-1

我正在使用 Excel 2007,并且在几乎相同的代码段中遇到了同样的问题。启用“Microsoft Scripting Runtime”应该可以解决它(主菜单>工具>参考),它对我有用。

于 2014-10-14T13:59:37.827 回答