2012-06-15 186 views
0

我正在使用Excel 2003 &我在宏中有以下代碼。VBA ReadLine從文件讀取時出錯

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 

當我執行這一點,就說明

"Runtime Error:5"

Invalid Procedure Call or argument at OpenTextFile

+3

定義常量ForReading = 1.查看代碼[here](http://stackoverflow.com/questions/1722196/what-is-dim-fso-myfile-filename-textline-in-vba)。 – deusxmach1na

+0

@ deusxmach1na:謝謝你。有用。請把它作爲答案,以便我可以接受它。 – logan

回答

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 
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 
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 
+0

酷!你有關於使用For Binary的教程的鏈接嗎?它看起來很有趣。 – deusxmach1na

+0

@ deusxmach1na:網上有很多。這是我遇到的第一個... http://www.vb6.us/tutorials/reading-and-writing-binary-files-visual-basic –

+0

@SiddharthRout你給的鏈接是VB。這也適用於VBA嗎? – logan

-1

我使用的是Excel 2007,並且在接近相同的代碼段時遇到了同樣的問題。啓用'Microsoft腳本運行時'應該可以解決它(主菜單>工具>參考),它爲我工作。