FileSearchオブジェクトの使い方

Access 2000でサポートされた、FileSearchオブジェクトの使い方を解説します。このオブジェクトを使用すると、任意のパス(ドライブ名、フォルダ)のファイルを検索(ワイルドカード指定も可能)することができます。

使用例1
この例では、D:\Temp2のフォルダのデータベースファイル(*.mdb)を検索します。イミディエイトウインドウから実行する前に、ツールメニューから参照設定をクリックして、オブジェクトの一覧から Microsoft Office 9.0 Object Libraryを選択してOKボタンをクリックしてください。

Sub FileSearch_EX()
' Set Microsoft Office 9.0 Object Library before Executing this Sub
  Dim intI As Integer
  With Application.FileSearch
    .NewSearch
    .LookIn = "D:\Temp2"
    .SearchSubFolders = True
    .FileName = "*.mdb"
    .MatchTextExactly = True
    .FileType = msoFileTypeAllFiles
  End With
  
  With Application.FileSearch
    If .Execute() > 0 Then
        Debug.Print "There were " & .FoundFiles.Count & _
            " file(s) found."
        For intI = 1 To .FoundFiles.Count
            Debug.Print .FoundFiles(intI)
        Next intI
    Else
        Debug.Print "There were no files found."
    End If
  End With
End Sub


使用例2
この例では、C:\Tempの全ファイル(*.*)を検索してファイルの拡張子を昇順にソートして表示します。

Sub FileSearch2_EX()
  Dim intI As Integer
  With Application.FileSearch
    .NewSearch
    .LookIn = "C:\Temp"
    .FileName = "*.*"
  End With
  
  With Application.FileSearch
    If .Execute(msoSortByFileType, msoSortOrderAscending, True) > 0 Then
        Debug.Print "There were " & .FoundFiles.Count & _
            " file(s) found."
        For intI = 1 To .FoundFiles.Count
            Debug.Print .FoundFiles(intI)
        Next intI
    Else
        Debug.Print "There were no files found."
    End If
  End With
End Sub


使用例3
この例では、C:\Tempの全ファイル(*.*)を検索してファイルサイズの降順にソートして表示します。尚、ファイルサイズはMB単位に変換しています。

Sub FileSearch3_EX()
  Dim intI As Integer
  Dim sngSizeMB As Single
  
  With Application.FileSearch
    .NewSearch
    .LookIn = "C:\Temp"
    .FileName = "*.*"
  End With
  
  With Application.FileSearch
    If .Execute(msoSortBySize, msoSortOrderDescending, True) > 0 Then
        Debug.Print "There were " & .FoundFiles.Count & _
            " file(s) found."
        For intI = 1 To .FoundFiles.Count
            sngSizeMB = FileLen(.FoundFiles(intI)) / (1024 ^ 2)
            Debug.Print .FoundFiles(intI), Round(CDec(sngSizeMB), 3) & " MB"
        Next intI
    Else
        Debug.Print "There were no files found."
    End If
  End With
End Sub