0

I'm writing a subroutine that needs to extract text from files in a directory. The routine is below. It works as long as there is only one file in the directory. When there are more than one, it tells me Set intFSO = intFSO.OpenTextFile(filePath, 1) line below.

I assume there is something I need to be doing to reset for the next file but I cannot seem to figure out what it is. Any tips?

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

There is more to this script. The routine above is called recursively in order to traverse the sub directories. All of that is working fine.

4

1 回答 1

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

FileSystemObject如果您打算在下一次迭代中再次使用它,请不要用文件句柄替换您的实例。为文件使用不同的变量。并删除整个路径连接/ OpenTextFileshebang。您可以直接从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
于 2017-10-18T01:14:29.073 回答