问题
I have a macro that iterate through folders and use the "dir"-function to find out if a file exist in the active folder, and puts the filename in a cell.
The problem is that it might be two or more files satisfies the search.
Dir(subfolder & "\Kommunesvar*")
How can I get both two results in a specified subfolder if there are two files starting with "Kommunesvar"? Dir returns the filename, but I want both.
回答1:
How are you using DIR. The below code will give you all the files which start with Kommunesvar and are Excel Files.
Option Explicit
Sub Sample()
Dim subfolder As String
Dim sDir
subfolder = "C:\Temp"
sDir = Dir$(subfolder & "\Kommunesvar*.xls*", vbNormal)
Do Until LenB(sDir) = 0
Debug.Print subfolder & sDir
sDir = Dir$
Loop
End Sub
If you want to store all the files names in one variable then you can use this as well.
Sub Sample()
Dim subfolder As String, FileNames As String
Dim sDir
subfolder = "C:\Temp"
sDir = Dir$(subfolder & "\Kommunesvar*.xls*", vbNormal)
Do Until LenB(sDir) = 0
If FileNames <> "" Then
FileNames = FileNames & "; " & subfolder & sDir
Else
FileNames = subfolder & sDir
End If
sDir = Dir$
Loop
Debug.Print FileNames
End Sub
来源:https://stackoverflow.com/questions/11291573/searching-for-files-with-dir-multiple-hits