Excel VBA DIR只循环一次

我创build了一个VBA循环通过存储文件夹中的Excel文件。 它只能通过文件名中含有“BAD”的字符来循环。 我的问题是DIR似乎只能工作一次? 在StrFile = Dir行之后的StrFile =“”。 我已经尝试了StrFile = Dir()StrFile = Dir(StrFile)

  If Application.FileDialog(msoFileDialogFolderPicker).Show <> 0 Then TheFolder = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) Dim StrFile As String StrFile = Dir(TheFolder & "\BAD *") Do While Len(StrFile) > 0 'Do Something StrFile = Dir 'Check next file. 'This is where it fails, it doesn't check the 2nd file Loop Else End End If 

更新:我注意到可能是问题的原因,我不熟悉DIR()。

在Do内部虽然脚本说'Do Something实际上是对另一个函数的调用,并且该函数有一个Example = Dir(ThePath) 。 当我尝试注释或禁用对该函数的调用时,该脚本将起作用。 所以我猜DIR只能用一次? 如果您使用DIR()循环通过文件夹中的文件,您不能使用另一个/不同的DIR()?

这遍历文件夹中的每个文件,并检查它是否感兴趣(在这种情况下,如果它是一个CSV – 使用If Lcase(Left(thing.path, 4)) = "bad " then为您的要求。

 Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFolder("c:\windows") For Each thing in f.files If LCase(Right(thing.path, 3)) = "csv" Then msgbox thing.path Set doc = GetObject(thing.path) msgbox Doc.name Doc.close Set Doc = Nothing End If Next 

如果您阅读帮助它说使用FSO而不是本机function。

Visual Basic的新function是文件系统对象(FSO)对象模型,它提供了一个基于对象的工具来处理文件夹和文件。 这使您可以使用熟悉的object.method语法,除了使用传统的Visual Basic语句和命令外,还可以使用一组丰富的属性,方法和事件来处理文件夹和文件。