用于从列范围复制公式的宏/vba 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25859173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:32:58  来源:igfitidea点击:

macro/vba code to copy down formula from range of columns

excel-vbavbaexcel

提问by Riaz

I have a formula in cells D4 to L4 and I would like to copy them down to the last row of column A that has data in it.

我在单元格 D4 到 L4 中有一个公式,我想将它们复制到包含数据的 A 列的最后一行。

Following code does work only for single column but I need range of columns (D4:L4). Can someone please help me out how to change following code.

以下代码仅适用于单列,但我需要列范围 (D4:L4)。有人可以帮助我了解如何更改以下代码。

Sub copyFormula() 
    Dim r1 As Range, r2 As Range, m As Long 
    Set r1 = Range("N2") 
    m = Cells(Rows.Count, "A").End(xlUp).Row 
    Set r2 = Range("N3:N" & m) r1.Copy r2 
End Sub

Thanks,

谢谢,

回答by teylyn

Move the last statement into its own row.

将最后一个语句移到它自己的行中。

    Set r2 = Range("N3:N" & m)
    r1.Copy r2
End Sub

That way the code runs fine from a Sheet module. If you want to run it from a normal module, you will need to qualify the ranges, for example like this:

这样代码在 Sheet 模块中运行良好。如果要从普通模块运行它,则需要限定范围,例如:

Sub copyFormula()
    Dim r1 As Range, r2 As Range, m As Long
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set r1 = ws.Range("N2")
    m = ws.Cells(Rows.Count, "A").End(xlUp).Row
    Set r2 = ws.Range("N3:N" & m)
    r1.Copy r2
End Sub