|
|
本帖最后由 qdchyq 于 2025-4-9 20:28 编辑
jjmysjg 发表于 2025-4-7 21:28
数据源B3向下的名称,能自动提取各源表不重复的到汇总表、然后在合并C列吗
Sub ExtractAndSumData2222()
Dim folderPath As String
Dim fileName As String
Dim summaryWb As Workbook
Dim summaryWs As Worksheet
Dim sourceWb As Workbook
Dim sourceWs As Worksheet
Dim i As Long, j As Long, col As Long
Dim matchValue As Variant
Dim tempDict As Object
Dim allNamesDict As Object
Dim key As Variant
Dim rowCount As Long
' 设置汇总表工作簿和工作表
Set summaryWb = ThisWorkbook
Set summaryWs = summaryWb.ActiveSheet
' 选择文件夹
With Application.fileDialog(msoFileDialogFolderPicker)
.Title = "选择包含 Excel 文件的文件夹"
If .Show = -1 Then
folderPath = .SelectedItems(1)
Else
MsgBox "未选择文件夹,操作取消。"
Exit Sub
End If
End With
' 添加文件夹路径分隔符
If Right(folderPath, 1) <> "\" Then
folderPath = folderPath & "\"
End If
' 创建一个字典用于存储所有出现过的名称
Set allNamesDict = CreateObject("Scripting.Dictionary")
' 获取文件夹中的第一个 Excel 文件
fileName = Dir(folderPath & "*.xls*")
' 遍历文件夹中的所有 Excel 文件
Do While fileName <> ""
' 排除汇总工作簿
If fileName <> summaryWb.Name Then
' 打开工作簿
Set sourceWb = Workbooks.Open(folderPath & fileName)
' 遍历工作簿中的所有工作表
For Each sourceWs In sourceWb.Sheets
' 遍历当前工作表 B3:B38 区域
For j = 3 To 38
matchValue = sourceWs.Cells(j, 2).Value
If matchValue <> "" And Not allNamesDict.Exists(matchValue) Then
allNamesDict.Add matchValue, 1
End If
Next j
Next sourceWs
' 关闭工作簿,不保存更改
sourceWb.Close SaveChanges:=False
End If
' 获取下一个 Excel 文件
fileName = Dir
Loop
' 将所有不重复的名称写入汇总表 B3:B38
rowCount = 3
For Each key In allNamesDict.Keys
summaryWs.Cells(rowCount, 2).Value = key
rowCount = rowCount + 1
If rowCount > 38 Then Exit For
Next key
col = 3 ' 从 C 列开始写入数据
fileName = Dir(folderPath & "*.xls*") ' 重新开始遍历文件
' 再次遍历文件夹中的所有 Excel 文件进行求和操作
Do While fileName <> ""
' 排除汇总工作簿
If fileName <> summaryWb.Name Then
' 打开工作簿
Set sourceWb = Workbooks.Open(folderPath & fileName)
' 创建一个字典用于存储每个名称对应的总和
Set tempDict = CreateObject("Scripting.Dictionary")
' 遍历工作簿中的所有工作表
For Each sourceWs In sourceWb.Sheets
' 遍历当前工作表 B3:B38 区域
For j = 3 To 40
matchValue = sourceWs.Cells(j, 2).Value
If Not tempDict.Exists(matchValue) Then
tempDict.Add matchValue, sourceWs.Cells(j, 3).Value
Else
tempDict(matchValue) = tempDict(matchValue) + sourceWs.Cells(j, 3).Value
End If
Next j
Next sourceWs
' 将汇总值写入汇总表对应列
For i = 3 To 40
matchValue = summaryWs.Cells(i, 2).Value
If tempDict.Exists(matchValue) Then
summaryWs.Cells(i, col).Value = tempDict(matchValue)
End If
Next i
' 写入文件名到第二行
summaryWs.Cells(2, col).Value = Replace(fileName, ".xlsx", "")
summaryWs.Cells(2, col).Value = Replace(summaryWs.Cells(2, col).Value, ".xls", "")
col = col + 1 ' 移动到下一列
' 关闭工作簿,不保存更改
sourceWb.Close SaveChanges:=False
End If
' 获取下一个 Excel 文件
fileName = Dir
Loop
End Sub
|
评分
-
1
查看全部评分
-
|