如何简化以下VBA代码?

时间:2017-04-28 15:51:46

标签: excel-vba vba excel

如何简化以下代码?

Range("C2").Copy
Range("C2", "C" & LastRow).Select
ActiveSheet.Paste
Range("E2", "E" & LastRow).Select
ActiveSheet.Paste
Range("H2", "H" & LastRow).Select
ActiveSheet.Paste
Range("K2", "K" & LastRow).Select
ActiveSheet.Paste
Range("O2", "O" & LastRow).Select
ActiveSheet.Paste
Range("Q2", "Q" & LastRow).Select
ActiveSheet.Paste

我想我应该能够选择范围并粘贴两行代码,但我无法弄清楚如何去做。

1 个答案:

答案 0 :(得分:0)

可能会出现以下情况?

Private Sub CommandButton1_Click()
    Dim LastRow As Long
    Dim WhatToCopy As String 'or whatever
    Dim RowRange As Range
    Dim ColumnRange As Range
    Dim rIntersection As Range
    Dim rCell As Range

    LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

    WhatToCopy = Worksheets("Sheet1").Cells(2, 3).Value
    Set RowRange = Worksheets("Sheet1").Rows("2:" & LastRow)
    Set ColumnRange = Application.Union(Columns("C"), Columns("E"), Columns("H"), Columns("K"), Columns("O"), Columns("Q"))
    Set rIntersection = Application.Intersect(RowRange, ColumnRange)

    For Each rCell In rIntersection.Cells
        rCell.Value = WhatToCopy
    Next
End Sub