从文件读取时VBA ReadLine错误

时间:2012-06-15 13:52:23

标签: excel-vba runtime-error excel-2003 filesystemobject vba

我正在使用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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:-1)

我正在使用Excel 2007,并且在相同的代码段附近遇到了同样的问题。启用Microsoft脚本运行时&#39;应该解决它(主菜单&gt;工具&gt;参考),它对我有用。