|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
- Sub MergeWorksheets()
- Dim folderPath As String
- Dim fileName As String
- Dim workbook As Workbook
- Dim worksheet As Worksheet
- Dim masterWorkbook As Workbook
- Dim masterWorksheet As Worksheet
- Dim lastRow As Long
- Dim lastCol As Long
- Dim i As Long
- Dim targetSheetName As String
- Dim cell As Range
-
- ' 设置文件夹路径
- folderPath = InputBox("请输入包含Excel文件的文件夹路径:")
- If folderPath = "" Then Exit Sub
-
- ' 设置目标工作表名称
- targetSheetName = InputBox("请输入要合并的工作表名称:")
- If targetSheetName = "" Then Exit Sub
-
- ' 创建新的主工作簿
- Set masterWorkbook = Workbooks.Add
- Set masterWorksheet = masterWorkbook.Sheets(1)
- masterWorksheet.Name = targetSheetName
-
- ' 遍历文件夹中的所有Excel文件
- fileName = Dir(folderPath & "\*.xls*")
-
- Do While fileName <> ""
- ' 打开工作簿
- Set workbook = Workbooks.Open(folderPath & "" & fileName)
-
- ' 检查是否存在目标工作表
- On Error Resume Next
- Set worksheet = workbook.Sheets(targetSheetName)
- On Error GoTo 0
-
- If Not worksheet Is Nothing Then
- ' 如果主工作表为空,复制表头
- If masterWorksheet.UsedRange.Rows.Count = 1 And IsEmpty(masterWorksheet.Cells(1, 1)) Then
- worksheet.Rows(1).Copy Destination:=masterWorksheet.Rows(1)
- End If
-
- ' 获取数据范围
- lastRow = worksheet.Cells(worksheet.Rows.Count, 1).End(xlUp).Row
- lastCol = worksheet.Cells(1, worksheet.Columns.Count).End(xlToLeft).Column
-
- ' 复制数据(包括隐藏的行)
- worksheet.Range(worksheet.Cells(2, 1), worksheet.Cells(lastRow, lastCol)).Copy
-
- ' 粘贴到主工作表
- lastRow = masterWorksheet.Cells(masterWorksheet.Rows.Count, 1).End(xlUp).Row
- masterWorksheet.Cells(lastRow + 1, 1).PasteSpecial xlPasteValues
- masterWorksheet.Cells(lastRow + 1, 1).PasteSpecial xlPasteFormats
-
- ' 复制列宽
- For i = 1 To lastCol
- masterWorksheet.Columns(i).ColumnWidth = worksheet.Columns(i).ColumnWidth
- Next i
- End If
-
- ' 关闭工作簿
- workbook.Close SaveChanges:=False
-
- ' 获取下一个文件名
- fileName = Dir()
- Loop
-
- ' 应用自动筛选
- masterWorksheet.UsedRange.AutoFilter
-
- ' 保存并关闭主工作簿
- masterWorkbook.SaveAs folderPath & "\合并结果_" & targetSheetName & ".xlsx"
- masterWorkbook.Close SaveChanges:=True
-
- MsgBox "合并完成!结果保存在:" & folderPath & "\合并结果_" & targetSheetName & ".xlsx"
- End Sub
复制代码 |
评分
-
2
查看全部评分
-
|