|
Sub ConsolidateDataFromSelectedFolder正确()
Dim folderPath As String
Dim fileName As String
Dim workBk As Workbook
Dim sourceSheet As Worksheet
Dim destSheet As Worksheet
Dim lastRow As Long
Dim i As Long
' 提示用户选择文件夹
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "请选择一个文件夹"
.Show
If .SelectedItems.Count = 0 Then
MsgBox "没有选择文件夹,程序将退出。", vbExclamation, "错误"
Exit Sub
End If
folderPath = .SelectedItems(1) & "\"
End With
' 在汇总工作簿中创建新的工作表用于存放汇总数据
Set destSheet = ThisWorkbook.Sheets.Add
destSheet.Name = "汇总表"
' 初始化行号
lastRow = 1
' 遍历文件夹中的所有文件
fileName = Dir(folderPath & "*.xlsx")
Do While fileName <> ""
' 打开工作簿
Set workBk = Workbooks.Open(folderPath & fileName)
' 遍历每个工作表,检查是否为需要的工作表
For i = 1 To workBk.Sheets.Count
Select Case workBk.Sheets(i).Name
Case "三步", "水迳", "水下"
' 设置源工作表和目标工作表
Set sourceSheet = workBk.Sheets(i)
Set destSheet = ThisWorkbook.Sheets("汇总表")
' 复制数据到汇总工作表,仅复制值,不复制公式
destSheet.Range("A" & lastRow).Resize(sourceSheet.Range("A15:I100").Rows.Count, sourceSheet.Range("A15:I100").Columns.Count).Value = sourceSheet.Range("A15:I100").Value
' 在 A 列写入工作表名称
destSheet.Range("A" & lastRow, "A" & lastRow + sourceSheet.Range("A15:I100").Rows.Count - 1) = workBk.Sheets(i).Name
' 提取标题并写入到 A1 行
destSheet.Range("A1:P1") = sourceSheet.Range("A15:P14").Value
' 更新行号
lastRow = lastRow + sourceSheet.Range("A15:I100").Rows.Count
End Select
Next i
' 关闭工作簿,不保存更改
workBk.Close savechanges:=False
' 获取下一个文件名
fileName = Dir()
Loop
' 清理
Set workBk = Nothing
Set sourceSheet = Nothing
Set destSheet = Nothing
' 可选:自动调整汇总数据表的列宽
ThisWorkbook.Sheets("汇总表").Columns.AutoFit
MsgBox "数据汇总完成!", vbInformation, "完成"
End Sub
怎样把固定的工作表"三步", "水迳", "水下"改为动态引用汇总工作簿里面的班级表a列来获取我要提取的工作表?
|
|