Google
 

星期六, 6月 13, 2009

在VBA中搜尋檔案

1.方法1:
利用My.Computer.FileSystem.GetFiles取得符合條件的檔案, 例如:

For Each foundFile As String In My.Computer.FileSystem.GetFiles("D:\book", FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText("D:\book\FileList.txt", foundFile, True)
Next

這段程式碼會找出D:\book目錄中所有.txt檔,並記錄在D:\book\FileList.txt中.

2.方法2:
在VBA中利用Application.FileSearch搜尋, 例如:

With Application.FileSearch
.NewSearch
.LookIn = "D:\Temp"
.SearchSubFolders = True
.Filename = "*.xls"
.MatchTextExactly = True
.FileType = msoFileTypeAllFiles
End With

設定搜尋條件,在D:\Temp中搜尋*.xls檔.


With Application.FileSearch
If .Execute() > 0 Then
MsgBox "There were " & .FoundFiles.Count & " file(s) found."
lastfile = ""
For i = 1 To .FoundFiles.Count
MsgBox .FoundFiles(i)
Next i
Else
MsgBox "There were no files found."
End If
End With


列出所有找到的檔案名稱.

沒有留言: