2017-10-17 169 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中,以表明它是从问题中引用的(当然不包括“下划线”)。 –