Sub SearchFileList()
Dim wsFileList As Worksheet, wsFind As Worksheet
Dim searchTerm As String
Dim lastRow As Long, i As Long, outputRow As Long
Dim fullPath As String, fileName As String, folderPath As String
Dim searchInFullPath As Boolean
Set wsFileList = ThisWorkbook.Sheets("filelist")
Set wsFind = ThisWorkbook.Sheets("find")
searchTerm = Trim(wsFind.Range("A1").Value)
If Len(searchTerm) = 0 Then
MsgBox "検索語が空です", vbExclamation
Exit Sub
End If
' 検索対象の判定:先頭が \ ならフルパス検索
If Left(searchTerm, 1) = "\" Then
searchTerm = Mid(searchTerm, 2) ' 先頭の \ を除去
searchInFullPath = True
Else
searchInFullPath = False
End If
wsFind.Range("A2:B1000").ClearContents
lastRow = wsFileList.Cells(wsFileList.Rows.Count, "A").End(xlUp).Row
outputRow = 2
For i = 1 To lastRow
fullPath = Trim(wsFileList.Cells(i, 1).Value)
fileName = Mid(fullPath, InStrRev(fullPath, "\") + 1)
folderPath = Left(fullPath, InStrRev(fullPath, "\") - 1)
If searchInFullPath Then
If InStr(1, fullPath, searchTerm, vbTextCompare) > 0 Then
wsFind.Cells(outputRow, "A").Value = fileName
wsFind.Cells(outputRow, "B").Value = folderPath
outputRow = outputRow + 1
End If
Else
If InStr(1, fileName, searchTerm, vbTextCompare) > 0 Then
wsFind.Cells(outputRow, "A").Value = fileName
wsFind.Cells(outputRow, "B").Value = folderPath
outputRow = outputRow + 1
End If
End If
Next i
If outputRow = 2 Then
wsFind.Range("A2").Value = "一致するファイルが見つかりませんでした"
End If
End Sub