在不知道您的工作簿(您称它们为文件)使用什么约定的情况下,我创建了一个宏,它可以按照您的要求进行操作,但会做出一些假设。这完全按照您的要求进行,但可能需要根据您的文件进行一些更改。
假设:
- 所有工作簿标题行
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 添加到您的工作簿,您必须打开PARENT Workbook,从菜单中选择Developer Tab
,从左侧菜单中打开,然后将代码粘贴到那里。Visual Basic
Sheet 1
以下是我在测试期间使用的工作簿的一些图像(ParentWorkbook、FileA、FileB):
运行宏之前的所有三个工作簿:
运行宏后的父工作簿:
请注意,此代码是快速创建的,并且已经完成了有限的测试。它当然可以被清理掉,代码中的冗余也可以被移除;它的目的是让你开始。如果您对任何部分有任何疑问,我很乐意解释。