2013-05-21 57 views
1

我有一個宏(Loop through files in a folder using VBA?),它查找zip文件的文件夾內部,但問題是最後一個zip文件有一個空字符串作爲名稱。我怎樣才能避免這個錯誤。Excel:搜索文件夾內的所有zip文件

宏的代碼:

Sub LoopThroughFiles() 
    ' Define variables 
    Dim file As String, folder As String 

    ' Define working directory 
    folder = "C:\Users\cportocarrero\Desktop\Curvas\" 

    ' Define type of file to search for 
    file = Dir(folder & "*.zip") 

    ' Loop through all the files 
    Do While Len(file) > 0 
     Debug.Print file 
     file = Dir 
     MsgBox file 
    Loop 
End Sub 
+1

你的問題是,你是Debug.Printing一個'file'的值,但是你在發送到MsgBox之前改變''file'變量。 KekuSemau的答案顯示了你的循環應該如何構建。你的'While'測試不需要改變,因爲'Len(file)> 0'與'file <>「有相同的效果''' – DeanOC

回答

1

你必須保持這樣的循環:
- 循環之前第一次調用dir,然後
- while循環
- 來電dir應該是循環內的最後一個命令

file = Dir(folder & "*.zip") 
Do While file <> "" 
    Debug.Print file 
    MsgBox file 
    file = Dir 
Loop 

dir retu rns一個空字符串,這意味着沒有更多的匹配。

+2

+1我在這裏很挑剔,但是調用'Dir' *應該*是循環內的最後一個命令,但不是*有*。它只需要在'file'變量的所有用法之後。 – DeanOC

+0

是的,你完全正確。 +1因爲挑剔,我編輯過。 – KekuSemau

相關問題