VBA 从列范围粘贴到多个范围的宏

VBA macro to paste from column range to multiple ranges

我正在尝试从 F 列中的某个范围复制一个公式,然后将其粘贴到每一列到该范围的最后一列。

粘贴到范围时,复制的单元格只会粘贴到 F 列,而不是所选范围。

代码:

Dim lastrow As Long
Dim lastcol As Long
Dim i As Long
Range("f2:f" & lastrow).Select
Selection.Copy
lastcol = Cells(6, Columns.Count).End(xlToLeft).Column
Range("f2:f" & lastrow).Select
With ActiveCell
    .Resize(lastrow, lastcol - 6).Select
End With

Selection.PasteSpecial xlPasteFormulas

首先,你lastrow没设置好!您必须为其分配一个值,如下所示:

lastrow = Cells(Rows.Count, 6).End(xlUp).Row

这将找到 F 列中的最后一行。

现在,只需使用 Range("f2:f" & lastrow).Copy 即可避免 Select 建议)。

要将其粘贴到最后一列,您必须这样做:

Range(Cells(2, lastcol), Cells(lastrow, lastcol).PasteSpecial xlPasteFormulas

综上所述,请改用此代码:

Option Explicit
Sub CopyRange()
    'use camel case or underscores for better readability
    Dim lastRow As Long, lastCol As Long
    lastRow = Cells(Rows.Count, 6).End(xlUp).Row
    'I changed the row here to second row (instead of 6th)
    lastCol = Cells(2, Columns.Count).End(xlToLeft).Column

    Range("f2:f" & lastrow).Copy
    Range(Cells(2, lastCol), Cells(lastRow, lastCol).PasteSpecial xlPasteFormulas
End Sub

附加说明:我将其包装在 Sub 中并使用了 Option Explicit,这也是避免 运行 时错误的建议。