我有一个代码可以列出文件夹中的项目。一段时间运行后,它给出了#N / A的文件太多。我想限制它正在搜索的文件。我不需要.JPG
和.TIFF
。如何仅将搜索指向.PDF,.DOC,.XLS等?
我尝试过:
MyFileName = Dir(Key & "*.PDF" Or "*.DOC" Or ".DOCX" Or ".XLS")
这是我的代码:
For Each Key In AllFolders.keys
'MyFileName = Dir(Key & "*.*")
MyFileName = Dir(Key & "*.PDF") 'only PDF files
Do While MyFileName <> ""
AllFiles.Add (Key & MyFileName), ""
MyFileName = Dir
Loop
Next
答案 0 :(得分:2)
DIR不接受多个文件扩展名的“掩码”,但是构建自己的扩展名无关紧要。
Dim ext As String, myFileName As String
For Each key In AllFolders.keys
myFileName = Dir(key & "*.*")
Do While myFileName <> vbNullString
ext = Mid(myFileName, InStrRev(myFileName, Chr(46)))
Select Case LCase(ext)
Case ".pdf", ".doc", ".docx", ".xls"
Debug.Print myFileName
AllFiles.Add (key & myFileName), vbNullString
Case Else
'do nothing
End Select
myFileName = Dir
Loop
Next key
答案 1 :(得分:1)
要将集合中的文件列表限制为特定文件,可以修改Do
循环:
Do While myFileName <> ""
If myFileName Like "*.PDF" Or _
myFileName Like "*.DOC" Or _
myFileName Like "*.XLS" Then
AllFiles.Add (Key & myFileName), ""
End If
myFileName = Dir
Loop
但是,这似乎是XY Problem
您真正的问题应该是为什么会遇到#NA
错误。