2012-07-02 46 views
1

我有一個遍歷文件夾的宏,並使用「dir」功能查找活動文件夾中是否存在文件,並將文件名放入單元格中。使用dir搜索文件 - 多個匹配

問題是,它可能是兩個或更多文件滿足搜索。

Dir(subfolder & "\Kommunesvar*") 

如果有兩個文件以「Kommunesvar」開頭,我該如何在指定的子文件夾中同時得到兩個結果? Dir返回文件名,但我想都是。

回答

2

你是怎麼用DIR的。以下代碼將爲您提供以Kommunesvar開頭並且是Excel文件的所有文件。

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 

如果您想要將所有文件名存儲在一個變量中,那麼您也可以使用它。

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 
+0

這是完美:)我需要一個宏來遍歷260個文件夾,並創建一個超鏈接到滿足指定字符串的每個文件,在對應活動文件夾的行中。像現在的魅力一樣工作:) –