首页 > 解决方案 > 需要 Excel VBA 将 B、C、D 列复制到 A 列

问题描述

我有问题需要你的帮助。我需要代码 VBA 将 B、C 列复制到 A 列,附上图片。有人可以给我一个解决方案吗?

在此处输入图像描述

标签: excelvba

解决方案


我建议以下代码:

Sub consolidateColumns()

Dim lr As Long, lr2 As Long

With ActiveSheet 'Replace with the worksheet you need, avoid using ActiveSheet
    lr = .Cells(Rows.Count, 1).End(xlUp).Row

    For i = 2 To 3 'Adjust the 3 to however many columns you need
        lr2 = .Cells(Rows.Count, i).End(xlUp).Row
        .Range(.Cells(1, i), .Cells(lr2, i)).Cut .Cells(lr + 1, 1)
        lr = lr + lr2
    Next i
End With
Application.CutCopyMode = False

End Sub

为了使其更短,但一开始更难阅读,您还可以使用以下代码:

Sub consolidateColumns()

With ActiveSheet 'Replace with the worksheet you need, avoid using ActiveSheet
    For i = 2 To 3 'Adjust the 3 to however many columns you need
        .Range(.Cells(1, i), .Cells(.Cells(Rows.Count, i).End(xlUp).Row, i)).Cut .Cells(.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1)
    Next i
End With
Application.CutCopyMode = False

End Sub

推荐阅读