Dim path As String '外部文件夾路徑
path = "F:\vba"
'當不確定路徑的最後一位是不是"\"時,可以用如下代碼判斷:
If Right(path , 1) <> "\" Then
path = path & "\"
End If
'遍歷文件夾,獲取以".xlsx"結尾的文件
Dim count As Integer
Dim name As String
Dim file As String
count = 0
name = Dir(path & "*.xlsx")
Do While Len(name) <> 0
file = path + name
'處理...
'處理...
'處理...
'獲取文件夾中下一個符合條件的文件名
count = count + 1
For i = 0 To count
If i = 0 Then
name = Dir(path & "*.xlsx")
Else
name = Dir
End If
Next
Loop
本來獲取文件夾中下一個符合條件的文件名只需要 name = Dir 即可,但是這樣寫的時候,獲取到的是name = ""。
因爲在處理中又用到了Dir函數,所以用這種迂迴的方式遍歷文件夾。