在excel RC参考中使用变量

时间:2013-10-14 14:48:09

标签: excel-vba vba excel

我是VBA /宏编码新手。试图在RC引用中插入变量,但它不起作用。我不确定我在哪里犯了错误,任何指导都表示赞赏。

Dim var1 As Integer
Dim var2 As Integer
var1 = 1  'this changes dynamically in my actual program
var2 = 2  'this changes dynamically in my actual program
Range("A2").Select
'following doesn't work
ActiveCell.FormulaR1C1 = "=RC[var1]/RC[var2]"
'following works
ActiveCell.FormulaR1C1 = "=RC[1]/RC[2]"

2 个答案:

答案 0 :(得分:2)

变量不会在字符串文字中展开。您应该显式构建字符串:

ActiveCell.FormulaR1C1 = "=RC[" & CStr(var1) & "]/RC[" &CStr(var2) & "]"

答案 1 :(得分:0)

使用字符串连接(&):

ActiveCell.FormulaR1C1 = "=RC" & var1 & "/RC" & var2