搜尋此網誌

2020年9月4日 星期五

使用VBA在Folder中找出需要的檔案VBA code to loop through files in a folder (and sub folders)

 感謝 Excel Off The Grid提供的三種解決方案,我紀錄一種,其它的請參考以下網址,謝謝~~~

https://exceloffthegrid.com/vba-code-loop-files-folder-sub-folders/


Sub LoopAllFilesInAFolder()

'Loop through all files in a folder
Dim fileName As Variant
fileName = Dir("C:\Users\marks\Documents\")

While fileName <> ""
    
    'Insert the actions to be performed on each file
    'This example will print the file name to the immediate window
    Debug.Print fileName

    'Set the fileName to the next file
    fileName = Dir
Wend

End Sub

The code above can easily be adapted with the use of wildcard characters. For example:

'Loop through each file with an extension of ".xlsx"
fileName = Dir("C:\Users\marks\Documents\*.xlsx")
'Loop through each file containing the word "January" in the filename
fileName = Dir("C:\Users\marks\Documents\*January*")
'Loop through each text file in a folder
fileName = Dir("C:\Users\marks\Documents\*.txt")

沒有留言:

張貼留言