VBA - Do While 循环返回 Dir <Invalid procedure call or argument> [英] VBA - Do While Loop returns Dir <Invalid procedure call or argument>
问题描述
我正在循环遍历一个文件夹以获得完整的文件名地址(文件夹地址 + 文件名和扩展名).
I am running a loop through a folder in order to get the complete filename address (folders address + file name and extension).
我正在使用以下内容,但在某些时候 Dir 值是
I am using the following, but at some point the Dir value is <Invalid procedure call or argument>
recsFolder = Functions.GetFolder("C:")
recfile = recsFolder & "" & Dir(recsFolder & "*.rec*")
Do While Len(recfile) > 0
recfile = recsFolder & "" & Dir
Loop
在完成读取所有文件的循环之前抛出错误.
The error is thrown before the loop as completed reading all the files.
另一种方法,每次按 F8 时 Dir 都会改变
another approach and Dir is changing everytime I press F8
If Right(recsFolder, 1) <> "" Then recsFolder = recsFolder & ""
numFiles = 0
recfile = Dir(recsFolder)
While recfile <> ""
numFiles = numFiles + 1
recfile = Dir()
Wend
我正在尝试这种最新方法,但遇到了同样的错误.问题是,当我一行一行地运行代码 (F8) 时,我可以看到每次在 While 中运行新的代码行时 Dir 值都会发生变化.
I am trying this latest approach and I get the same error. The problem is that when I run the code line by line (F8) I can see that the Dir value changes everytime a new line of code is run inside the While.
推荐答案
代替 DIR,这个怎么样:
Instead of DIR, how about this:
' enable Tools->References, Microsoft Scripting Runtime
Sub Test()
Dim fso As New Scripting.FileSystemObject
Dim fldr As Folder
Set fldr = fso.GetFolder("C: est")
HandleFolder fldr
End Sub
Sub HandleFolder(fldr As Folder)
Dim f As File
Dim subFldr As Folder
' loop thru files in this folder
For Each f In fldr.Files
Debug.Print f.Path
Next
' loop thru subfolders
For Each subFldr In fldr.SubFolders
HandleFolder subFldr
Next
End Sub
这篇关于VBA - Do While 循环返回 Dir <Invalid procedure call or argument>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!