您好,万能的老师,EXCEL单元格区域A1:F13 如何通过VBA代码,把多列的数据合并成两列
时间: 2024-03-11 09:51:17 浏览: 171
您好,可以使用以下代码将多列数据合并成两列:
```
Sub MergeColumnsToTwo()
Dim lastRow As Long
Dim lastCol As Long
Dim i As Long
Dim j As Long
Dim k As Long
Dim l As Long
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
k = 1
l = 1
For j = 1 To lastCol Step 2
For i = 1 To lastRow
If Not IsEmpty(Cells(i, j)) And Not IsEmpty(Cells(i, j + 1)) Then
Cells(k, 1) = Cells(i, j)
Cells(k, 2) = Cells(i, j + 1)
k = k + 1
End If
Next i
Next j
For l = k To lastRow
Cells(l, 1) = ""
Cells(l, 2) = ""
Next l
End Sub
```
这段代码假设您的数据是从A1单元格开始的,并且每两列为一组需要合并的数据。代码会将每一组数据合并成一行,放在新的工作表中的两列中。如果有单元格为空,则该组数据将被忽略。如果最后一行不足以填充完整的一组数据,则会在新工作表中保留空行。
阅读全文