[英]Referencing a range on another sheet in vba code to copy a formula down to the last row of data
I have a workbook with two sheets.我有一本工作簿,里面有两张纸。 On sheet1 I have a column (A) for which I need to copy the formula in A2 down for as many rows as there are in sheet2 column (B).Currently I use the following code
在 sheet1 上,我有一个列 (A),我需要将 A2 中的公式向下复制到 sheet2 列 (B) 中的行数。目前我使用以下代码
Range("B3:B" & Cells(Rows.Count,"C").End(xlUp).Row).Formula = Range ("B2")
to do something similar but where the range referred to is on the same worksheet.做一些类似的事情,但所指的范围在同一个工作表上。 What I need to know is how to adapt this code to replace the "C" above with the range on sheet 2. Can someone please help?
我需要知道的是如何修改此代码以用表 2 上的范围替换上面的“C”。有人可以帮忙吗?
you could use:你可以使用:
With Sheet1 ' reference Sheet1 worksheet
.Range("B3:B" & Sheet2.Cells(Rows.Count, "B").End(xlUp).Row).Formula = .Range("B2").Formula
End With
to copy sheet1 cell B2 formula down as many rows as Sheet2 column B last not empty cell row index将 sheet1 单元格 B2 公式向下复制与 Sheet2 列 B 最后一个非空单元格行索引一样多的行
For every Range()
, Cells()
, Rows()
and Columns()
object specify in which sheet they are.对于每个
Range()
、 Cells()
、 Rows()
和Columns()
对象,指定它们在哪个工作表中。 Don't miss any of them or your code can randomly fail.不要错过任何一个,否则您的代码可能会随机失败。
Example例子
Worksheets("Sheet1").Range("A1") 'addresses cell A1 in Sheet1
You can use variables as references:您可以使用变量作为引用:
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
ws.Range("A1") 'now also addresses cell A1 in Sheet1
while尽管
Range("A1")
will address the sheet that has focus (is on top) while the code runs.将在代码运行时寻址具有焦点(位于顶部)的工作表。 Don't rely on this because this can easily change by a single mouse click of the user.
不要依赖于此,因为这可以通过用户单击鼠标轻松更改。 Therefore always specify which sheet you mean.
因此,请始终指定您的意思是哪个工作表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.