hiko-blog

VBA業務改善

MENU

フォルダ内、検索vbs

' FileSearchWithOutput.vbs

Dim folderPath, searchValue, outputFile
folderPath = InputBox("フォルダのパスを入力してください:")
searchValue = InputBox("検索する部分文字列を入力してください:")
outputFile = "output.txt"

If folderPath = "" Or searchValue = "" Then
    MsgBox "入力がキャンセルされたか、無効な値が入力されました。", vbExclamation, "エラー"
    WScript.Quit
End If

SearchFiles folderPath, searchValue

Sub SearchFiles(folderPath, searchValue)
    Dim objFSO, objFolder, objFile, result
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(folderPath)

    result = ""

    For Each objFile In objFolder.Files
        If InStr(1, UCase(objFSO.GetBaseName(objFile.Name)), UCase(searchValue)) > 0 Then
            result = result & objFile.Path & vbCrLf
            AppendToFile objFile.Path, outputFile
        End If
    Next

    If Len(result) > 0 Then
        MsgBox "一致するファイルが見つかりました:" & vbCrLf & result, vbInformation, "検索結果"
    Else
        MsgBox "一致するファイルは見つかりませんでした。", vbInformation, "検索結果"
    End If
End Sub

Sub AppendToFile(text, filePath)
    Dim objFSO, objFile
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    ' ファイルが存在しない場合は新規作成し、存在する場合は末尾に追加
    Set objFile = objFSO.OpenTextFile(filePath, 8, True)
    objFile.WriteLine text
    objFile.Close
End Sub