[英]Excel VBA for loop formula with relative cell reference
I am trying to start in cell "B2", put in a formula that takes the cell to the left of "B2", which is "A2", multiplied by a number on another sheet.. 我试图从“ B2”单元格开始,输入一个公式,该单元格将“ B2”左侧的单元格即“ A2”乘以另一张纸上的数字。
My problem is...how do I reference the cell to the left? 我的问题是...如何引用左侧的单元格? And also, how do I reference the cell on the other sheet?
而且,如何引用另一张纸上的单元格? I am pretty sure it will be the same answer, but I can't figure it out..
我很确定这将是相同的答案,但我无法弄清楚。
Sub RelFormula()
For Col = 1 To 2
For Row = 2 To 6
Cells(Row, Col).Formula = "=" & Cells.Offset(0, -1).Value & "*" worksheets("output").range("A1")
Next Row
Next Col
End Sub
You do not need the offset
, you can just -1 from the column argument of Cells
. 您不需要
offset
,只需从Cells
的列参数开始就-1。 You also missed off the row and column argument of Cells
used in the formula, the final &
, as comments pointed out. 正如注释所指出的,您还错过了公式中使用的
Cells
的行和列参数,最后一个&
。
Also, its a really bad idea using keywords, or reserved words as variables. 而且,使用关键字或保留字作为变量是一个非常糟糕的主意。 Some names are protected, and VBA will simply not compile/run if certain words are used as variables names - but for things like "Row", which are used in other places in VBA...it is asking for trouble (ie not recommended/bad practice, etc), and will be confusing to read/debug, etc.
有些名称受到保护,如果将某些单词用作变量名,则VBA根本不会编译/运行-但对于诸如“行”之类的东西(在VBA中的其他地方使用的话)……这很麻烦(即不建议使用/不良做法等),并且会造成读取/调试等混乱。
Also, consider using Option Explicit
(if you are not already) at the top of any code module. 另外,请考虑在任何代码模块的顶部使用
Option Explicit
(如果尚未使用)。 This will make VBA complain/stop if you do not define all of your variables. 如果您未定义所有变量,这将使VBA抱怨/停止。 It can be frustrating for beginners - but it is worth it in the long run.
对于初学者来说,这可能令人沮丧-但从长远来看,这是值得的。
I've rewritten your code, superficially, renaming and defining variables. 我已经从表面上重写了您的代码,重命名和定义了变量。 Technically you do not need the double (outer) loop (
c_loop
takes just one value): 从技术上讲,您不需要双(外)循环(
c_loop
仅取一个值):
Sub RelFormula()
Dim r_loop, c_loop As Integer
For c_loop = 2 To 2
For r_loop = 2 To 6
Cells(r_loop, c_loop).Formula = "=" & Cells(r_loop, c_loop - 1).Value _
& "*" & Worksheets("Sheet1").Range("A1").Value
Next r_loop
Next c_loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.