2017-10-17 103 views
0

我在寫一個子程序,需要從目錄中的文件中提取文本。例程如下。只要目錄中只有一個文件,它就會工作。當有多個時,它會告訴我Set intFSO = intFSO.OpenTextFile(filePath, 1)下面的一行。打開循環中的每個文件

我認爲有一些事情我需要做的重置下一個文件,但我似乎無法弄清楚它是什麼。有小費嗎?

Sub ExtractEDI(folPath) 
    Dim sName, fil 
    Dim intFSO 
    Dim filePath 

    Set intFSO = CreateObject("Scripting.FileSystemObject") 

    For Each fil In fso.GetFolder(folPath).Files 
    filePath = folpath & "\" & fil.Name 
    Set intFSO = intFSO.OpenTextFile(filePath, 1) 

    'will process file here 

    intFSO.Close 
    Next 
    Set intFSO = Nothing 
End Sub 

這個腳本還有更多。上面的例程是爲了遍歷子目錄而遞歸調用的。所有這一切工作正常。

回答

3
Set intFSO = intFSO.OpenTextFile(filePath, 1) 
' ^^^^^^ ^^^^^^ 

,如果你打算在接下來的迭代中再次使用它,不要與文件句柄替換您FileSystemObject實例。爲文件使用不同的變量。並放棄整個路徑連接/ OpenTextFile shebang。您可以直接從File對象打開文件。

這是你所需要的(假設fso是一家全球性FileSystemObject實例):

Sub ExtractEDI(folPath) 
    For Each fil In fso.GetFolder(folPath).Files 
    Set f = fil.OpenAsTextStream 

    'will process file here 

    f.Close 
    Next 
End Sub 
+0

這是有道理的。非常感謝。 – Quintin

+0

@lankymart我把第一個代碼片段放在一個blockquote中,以表明它是從問題中引用的(當然不包括「下劃線」)。 –