VBAでファイル検索を行う

  • 前提:あるフォルダの直下にあるファイルの中で、条件にあう名前のファイルを検索する
  • 方法:Dirを使う

      Dim dataFolder As String, buf As String
    
      buf = Dir(dataFolder & "\*.*")
      Do While buf <> ""
          If buf Like "sample*.txt" Then
              Debug.Print buf
          End If
          buf = Dir()
      Loop

  • 方法:FSOを使う

      Dim dataFolder As String, myFile As File
    
      For Each myFile In fso.GetFolder(dataFolder).Files
          If myFile.Name Like "sample*.txt" Then
              Debug.Print myFile.Name
          End If
      Next