ワークブック (ファイルと呼びます) がどのような規則を使用しているかを知らずに、私はあなたの要求どおりに動作するが、いくつかの仮定を行うマクロを作成しました。これはあなたが求めるとおりに機能しますが、ファイルに基づいていくつかの変更が必要になる場合があります。
仮定:
- すべてのワークブック ヘッダー行
IC
およびは、それぞれName
セルA1
およびにあります。B1
- このマクロを実行する前に、すべてのブックが開かれます
- マクロは
Parent Workbook
、最終結果を格納する WorkBook であると想定されるから開始されます。
- 各ワークブックのすべての値は、そのワークブックの最初のシートにあります
コード
Public Sub CombineAllOpenWorkbooks()
Dim parentWb As Workbook, childWb As Workbook
Dim destinationWs As Worksheet, sourceWs As Worksheet
Dim highestRowCount As Integer
Dim firstColumnRowCount As Integer
Dim secondColumnRowCount As Integer
Application.ScreenUpdating = False
'this holds reference to the parent workbook, which is where all the values go
Set parentWb = Application.Workbooks(ThisWorkbook.Name)
Set destinationWs = parentWb.Sheets(1)
'for each workbook open that isn't the aprent workbook, find the last cell,
'select it, copy its values, then paste them at the end of the parent workbooks
'current values
For Each childWb In Application.Workbooks
If childWb.Name <> parentWb.Name Then
Set sourceWs = childWb.Sheets(1)
firstColumnRowCount = sourceWs.Cells(Rows.Count, 1).End(xlUp).Row
secondColumnRowCount = sourceWs.Cells(Rows.Count, 2).End(xlUp).Row
highestRowCount = firstColumnRowCount
If firstColumnRowCount < secondColumnRowCount Then
highestRowCount = secondColumnRowCount
End If
'copy from below the 'IC/Name' headers to the last cell that contains values
sourceWs.Range(sourceWs.Cells(2, 1), sourceWs.Cells(highestRowCount, 2)).Copy
firstColumnRowCount = destinationWs.Cells(Rows.Count, 1).End(xlUp).Row
secondColumnRowCount = destinationWs.Cells(Rows.Count, 2).End(xlUp).Row
highestRowCount = firstColumnRowCount
If firstColumnRowCount < secondColumnRowCount Then
highestRowCount = secondColumnRowCount
End If
'paste the previously copied values to the end of the parent workbokos values
destinationWs.Range("A" & highestRowCount + 1).PasteSpecial Paste:=xlPasteValues
End If
Next childWb
Application.ScreenUpdating = True
End Sub
この VBA をワークブックに追加するにDeveloper Tab
は、PARENT ワークブックの を開き、メニューから選択Visual Basic
し、左側のメニューから開きSheet 1
、そこにコードを貼り付ける必要があります。
テスト中に使用したワークブックの画像を次に示します (ParentWorkbook、FileA、FileB)。
マクロを実行する前の 3 つのワークブックすべて:

マクロ実行後の親ワークブック:

このコードは迅速に作成され、限定的なテストが行われたことに注意してください。それは確かにクリーンアップでき、コード内の冗長性を取り除くことができます。その目的は、開始することです。どの部分でもご不明な点がございましたら、喜んでご説明いたします。