Sub フォルダ内bookシートの条件抽出()
Dim folderPath As String
Dim fileName As String
Dim wb As Workbook
Dim ws As Worksheet
Dim newWb As Workbook
Dim newWs As Worksheet
Dim lastRow As Long
Dim newRow As Long
Dim i As Long
Dim searchTextC As String
Dim searchTextZ As String
Dim targetSheet As String
Dim saveFileName As String
Dim dateTimeStamp As String
' フォルダのパスを指定
folderPath = "C:\YourFolderPath\" ' ここにフォルダパスを指定
searchTextC = "C列の条件" ' C列で検索する文字
searchTextZ = "Z列で検索する文字" ' Z列で検索する文字
targetSheet = "Sheet1" ' 対象のシート名
' 画面更新をオフにする
Application.ScreenUpdating = False
' 新しいブックを作成
Set newWb = Workbooks.Add
Set newWs = newWb.Worksheets(1)
newWs.Name = "FilteredData"
newWs.Cells(1, 1).Value = "ブック名"
newWs.Cells(1, 2).Value = "C列のデータ"
newWs.Cells(1, 3).Value = "Z列のデータ"
newRow = 2
' フォルダ内の全ファイルをループ
fileName = Dir(folderPath & "*.xls*")
Do While fileName <> ""
' ワークブックを開く
Set wb = Workbooks.Open(folderPath & fileName)
On Error Resume Next
Set ws = wb.Worksheets(targetSheet)
On Error GoTo 0
' 指定したシートが存在する場合
If Not ws Is Nothing Then
lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
' 行をループ
For i = 1 To lastRow
If InStr(ws.Cells(i, "C").Value, searchTextC) > 0 And InStr(ws.Cells(i, "Z").Value, searchTextZ) > 0 Then
newWs.Cells(newRow, 1).Value = wb.Name ' ブック名
newWs.Cells(newRow, 2).Value = ws.Cells(i, "C").Value ' C列のデータ
newWs.Cells(newRow, 3).Value = ws.Cells(i, "Z").Value ' Z列のデータ
newRow = newRow + 1
End If
Next i
End If
' ワークブックを閉じる
wb.Close SaveChanges:=False
fileName = Dir
Loop
' 現在の日付と時刻を取得してフォーマット
dateTimeStamp = Format(Now, "yyyymmdd_hhmmss")
saveFileName = Environ("USERPROFILE") & "\Desktop\FilteredData_" & dateTimeStamp & ".xlsx"
' デスクトップに保存
newWb.SaveAs saveFileName
newWb.Close
' 画面更新をオンにする
Application.ScreenUpdating = True
MsgBox "処理が完了しました!デスクトップに保存しました: " & saveFileName, vbInformation
End Sub