vba代码实现一个工作簿中多张工作表的合并(表中标题不规范,不同表的有的列不一样)
时间: 2023-12-31 12:05:04 浏览: 126
以下是 VBA 代码实现在一个工作簿中多张工作表的合并,处理表中标题不规范、不同表的列不一样的情况:
```vb
Sub MergeWorksheets()
Dim mergedWorksheet As Worksheet
Dim sourceWorksheet As Worksheet
Dim lastRow As Long
Dim lastColumn As Long
Dim destinationColumn As Long
Dim sourceColumn As Long
Dim sourceRow As Long
Set mergedWorksheet = Worksheets.Add(after:=Worksheets(Worksheets.Count))
mergedWorksheet.Name = "Merged Data"
destinationColumn = 1
For Each sourceWorksheet In ThisWorkbook.Worksheets
If sourceWorksheet.Name <> mergedWorksheet.Name Then
lastRow = sourceWorksheet.Cells(Rows.Count, 1).End(xlUp).Row
lastColumn = sourceWorksheet.Cells(1, Columns.Count).End(xlToLeft).Column
For sourceColumn = 1 To lastColumn
If WorksheetFunction.CountA(sourceWorksheet.Columns(sourceColumn)) > 1 Then
mergedWorksheet.Cells(1, destinationColumn).Value = sourceWorksheet.Cells(1, sourceColumn).Value
For sourceRow = 2 To lastRow
mergedWorksheet.Cells(sourceRow, destinationColumn).Value = sourceWorksheet.Cells(sourceRow, sourceColumn).Value
Next sourceRow
destinationColumn = destinationColumn + 1
End If
Next sourceColumn
End If
Next sourceWorksheet
End Sub
```
上述代码会新建一个名为“Merged Data”的工作表,将当前工作簿中的所有工作表中的数据合并到该工作表中。在合并过程中,会忽略标题行中的空单元格,只将非空单元格所处的列合并到目标表中,以避免不同表的列不一样的问题。
阅读全文