Option Explicit
Sub SearchAcrossBooks_OnePass()
Dim wsMain As Worksheet
Dim lastrow As Long, r As Long, endRow As Long
Dim dict As Object
Dim key As Variant, v As Variant
Dim Path As String, f As String
Dim wb As Workbook, ws As Worksheet
Dim rng As Range
Dim data As Variant
Dim i As Long, j As Long
Dim sc As Boolean, ev As Boolean, calc As XlCalculation
Dim cnt As Long
Dim FDL As FileDialog
Dim selFolder As String
' フォルダ選択ダイアログを作成
Set FDL = Application.FileDialog(msoFileDialogFolderPicker)
' ダイアログの初期フォルダ設定(オプション)
'FDL.InitialFileName = "C:\"
' ダイアログ表示し、フォルダが選択されたか確認
If FDL.Show = -1 Then
' 選択されたフォルダパスを取得
selFolder = FDL.SelectedItems(1)
Else
'フォルダ選択がキャンセルの場合
Exit Sub
End If
Set wsMain = ThisWorkbook.Sheets("判定")
lastrow = wsMain.Cells(wsMain.Rows.Count, "E").End(xlUp).Row
If lastrow < 2 Then Exit Sub
Set dict = CreateObject("Scripting.Dictionary")
For r = 2 To lastrow
v = wsMain.Cells(r, "E").Value
If Len(v) = 0 Then Exit For
dict(CStr(v)) = 0
Next r
endRow = r - 1
If dict.Count = 0 Then Exit Sub
sc = Application.ScreenUpdating
ev = Application.EnableEvents
calc = Application.Calculation
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
' 同一フォルダ内の他ブックを集計
Path = selFolder & "\"
f = Dir(Path & "*.xls*")
Do While f <> ""
If Path & f <> ThisWorkbook.FullName Then
On Error Resume Next
Set wb = Workbooks.Open(Path & f, ReadOnly:=True)
If Err.Number = 0 Then
On Error GoTo 0
Call CountInWorkbook(wb, dict)
wb.Close SaveChanges:=False
Else
Err.clear
On Error GoTo 0
End If
End If
f = Dir()
Loop
' 結果を書き戻し
For r = 2 To endRow
cnt = dict(CStr(wsMain.Cells(r, "E").Value))
Select Case cnt
'Case 0: wsMain.Cells(r, "A").Value = "×"
Case 1: wsMain.Cells(r, "A").Value = "◯"
'Case Else: wsMain.Cells(r, "A").Value = "△"
End Select
Next r
Application.ScreenUpdating = sc
Application.EnableEvents = ev
Application.Calculation = calc
End Sub
Private Sub CountInWorkbook(wb As Workbook, dict As Object)
Dim ws As Worksheet
Dim rng As Range
Dim data As Variant
Dim i As Long, j As Long
Dim v As Variant
For Each ws In wb.Worksheets
Set rng = ws.UsedRange
If Not rng Is Nothing Then
If rng.Cells.CountLarge > 1 Then
data = rng.Value
If IsArray(data) Then
For i = 1 To UBound(data, 1)
For j = 1 To UBound(data, 2)
v = data(i, j)
If dict.Exists(CStr(v)) Then
dict(CStr(v)) = dict(CStr(v)) + 1
End If
Next j
Next i
Else
v = data
If dict.Exists(CStr(v)) Then
dict(CStr(v)) = dict(CStr(v)) + 1
End If
End If
Else
v = rng.Value
If dict.Exists(CStr(v)) Then
dict(CStr(v)) = dict(CStr(v)) + 1
End If
End If
End If
Next ws
End Sub