Option Explicit
Sub てすと2データ転記()
Dim wsPath As Worksheet
Dim wsOutput As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim lastPathRow As Long
Dim lastDataRow As Long
Dim pathRow As Long
Dim sourceRow As Long
Dim outputRow As Long
Dim filePath As String
Dim rowData As Variant
Set wsPath = ThisWorkbook.Worksheets("Sheet1")
Set wsOutput = ThisWorkbook.Worksheets("Sheet2")
'Sheet2を初期化
wsOutput.Cells.ClearContents
'見出し
wsOutput.Range("A1:J1").Value = Array( _
"ファイルパス", _
"B列", "C列", "D列", "E列", "F列", _
"G列", "H列", "I列", "J列")
outputRow = 2
'Sheet1のA列にあるパスの最終行
lastPathRow = wsPath.Cells(wsPath.Rows.Count, "A").End(xlUp).Row
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
For pathRow = 2 To lastPathRow
Set wbSource = Nothing
Set wsSource = Nothing
filePath = Trim$(CStr(wsPath.Cells(pathRow, "A").Value))
If filePath = "" Then GoTo NextFile
If Dir(filePath) = "" Then GoTo NextFile
On Error GoTo FileError
'対象ブックを読み取り専用で開く
Set wbSource = Workbooks.Open( _
Filename:=filePath, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMru:=False, _
IgnoreReadOnlyRecommended:=True)
'「てすと2」シートを取得
Set wsSource = wbSource.Worksheets("てすと2")
'B:Jの中で最後にデータが存在する行を取得
lastDataRow = GetLastRowBJ(wsSource)
If lastDataRow >= 4 Then
For sourceRow = 4 To lastDataRow
rowData = wsSource.Range( _
wsSource.Cells(sourceRow, "B"), _
wsSource.Cells(sourceRow, "J") _
).Value
'B:Jのどこかにデータがあれば転記
If HasData(rowData) Then
'A列に元ファイルのフルパス
wsOutput.Cells(outputRow, "A").Value = filePath
'B:Jは列位置を維持してそのまま転記
wsOutput.Range( _
wsOutput.Cells(outputRow, "B"), _
wsOutput.Cells(outputRow, "J") _
).Value = rowData
outputRow = outputRow + 1
End If
Next sourceRow
End If
FileClose:
On Error Resume Next
If Not wbSource Is Nothing Then
wbSource.Close SaveChanges:=False
End If
Set wsSource = Nothing
Set wbSource = Nothing
On Error GoTo 0
NextFile:
Next pathRow
wsOutput.Columns("A:J").AutoFit
終了処理:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.AskToUpdateLinks = True
MsgBox _
"転記が完了しました。" & vbCrLf & _
"転記行数:" & outputRow - 2 & "行", _
vbInformation
Exit Sub
FileError:
'エラーが出たファイルも必ず閉じる
Resume FileClose
End Sub
Private Function GetLastRowBJ(ByVal ws As Worksheet) As Long
Dim foundCell As Range
Set foundCell = ws.Range("B:J").Find( _
What:="*", _
After:=ws.Range("B1"), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
If foundCell Is Nothing Then
GetLastRowBJ = 0
Else
GetLastRowBJ = foundCell.Row
End If
End Function
Private Function HasData(ByVal rowData As Variant) As Boolean
Dim i As Long
For i = LBound(rowData, 2) To UBound(rowData, 2)
If IsError(rowData(1, i)) Then
HasData = True
Exit Function
ElseIf Len(Trim$(CStr(rowData(1, i)))) > 0 Then
HasData = True
Exit Function
End If
Next i
HasData = False
End Function