|
楼主 |
发表于 2023-4-23 16:01
|
显示全部楼层
Sub SummarizeWorkbooksData()
Dim selectedFolder As Object
Dim queue As New Collection
' 选择待汇总求和的工作簿所在的文件夹
Set selectedFolder = Application.FileDialog(msoFileDialogFolderPicker)
selectedFolder.AllowMultiSelect = False
If selectedFolder.Show <> -1 Then Exit Sub
queue.Add selectedFolder.SelectedItems.Item(1)
' 创建汇总工作簿
Dim summaryWorkbook As Workbook
Set summaryWorkbook = Workbooks.Add
' 遍历队列中的文件夹
Do While queue.Count > 0
Dim currentFolder As String
currentFolder = queue.Item(1)
queue.Remove 1
' 遍历当前文件夹下的所有文件
Dim currentFile As String
currentFile = Dir(currentFolder & "\*.*")
Do While currentFile <> ""
' 判断文件类型:只处理xlsx和xls文件
If Right(currentFile, 4) = ".xlsx" Or Right(currentFile, 4) = ".xls" Then
Dim currentWorkbook As Workbook
Set currentWorkbook = Workbooks.Open(currentFolder & "\" & currentFile)
' 遍历工作簿中的所有工作表
Dim currentSheet As Worksheet
For Each currentSheet In currentWorkbook.Worksheets
Dim sheetName As String
sheetName = currentSheet.Name
' 在汇总工作簿中查找是否存在相同名称的工作表
Dim summarySheet As Worksheet
Set summarySheet = Nothing
On Error Resume Next
Set summarySheet = summaryWorkbook.Worksheets(sheetName)
On Error GoTo 0
If summarySheet Is Nothing Then
' 如果不存在相同名称的工作表,则在汇总工作簿中新建一个工作表
currentSheet.Copy after:=summaryWorkbook.Sheets(summaryWorkbook.Sheets.Count)
Set summarySheet = summaryWorkbook.Sheets(summaryWorkbook.Sheets.Count)
summarySheet.Name = sheetName
Else
' 如果已经存在相同名称的工作表,则将数字求和
Dim startRow As Long, startCol As Long, endRow As Long, endCol As Long
startRow = currentSheet.UsedRange.Row
startCol = currentSheet.UsedRange.Column
endRow = currentSheet.UsedRange.Row + currentSheet.UsedRange.Rows.Count - 1
endCol = currentSheet.UsedRange.Column + currentSheet.UsedRange.Columns.Count - 1
currentSheet.Range(currentSheet.Cells(startRow, startCol), currentSheet.Cells(endRow, endCol)).CurrentRegion.Copy
summarySheet.Range(summarySheet.Cells(startRow, startCol), summarySheet.Cells(endRow, endCol)).PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd
End If
Next currentSheet
' 关闭当前工作簿
currentWorkbook.Close False
ElseIf (GetAttr(currentFolder & "\" & currentFile) And vbDirectory) = vbDirectory And currentFile <> "." And currentFile <> ".." Then
' 如果是文件夹,则将其添加到队列中
queue.Add currentFolder & "\" & currentFile
End If
currentFile = Dir
Loop
Loop
End Sub
修改为选择性粘贴,可以累计一个文件夹的了。
谢谢老师们的帮助。 |
|