在循环中打开每个文件

时间:2017-10-17 20:57:06

标签: vbscript fso

我正在编写一个需要从目录中的文件中提取文本的子程序。例程如下。只要目录中只有一个文件,它就可以工作。当有多个时,它会告诉我下面的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

此脚本还有更多内容。上面的例程是递归调用的,以便遍历子目录。所有这些都很好。

1 个答案:

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