用vba写一段excel多sheet合并代码
时间: 2023-05-28 14:01:19 浏览: 117
Sub MergeSheets()
Dim ws As Worksheet
Dim wb As Workbook
Dim mergeRange As Range
Dim lastColumn As Integer
Dim lastRow As Integer
Dim i As Integer
Set wb = ActiveWorkbook '获取当前活动工作簿
'设置合并区域起始范围
Set mergeRange = wb.Sheets(1).UsedRange
'循环遍历每个工作表
For Each ws In wb.Worksheets
'排除第一个工作表
If ws.Index <> 1 Then
'获取当前工作表最后一列和最后一行的编号
lastColumn = ws.UsedRange.Columns(ws.UsedRange.Columns.Count).Column
lastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row
'将合并区域扩大以包含当前工作表数据
Set mergeRange = mergeRange.Resize(lastRow, lastColumn)
'将当前工作表数据复制到合并区域
mergeRange.Offset(mergeRange.Rows.Count, 0).Resize(lastRow, lastColumn).Value = ws.UsedRange.Value
End If
Next ws
'删除第一行空白数据
For i = mergeRange.Rows.Count To 1 Step -1
If WorksheetFunction.CountA(mergeRange.Rows(i)) = 0 Then
mergeRange.Rows(i).Delete
Else
Exit For
End If
Next i
End Sub
阅读全文