我想在VBA的C列中创建IF公式。但是,当我这样做时,公式的出现是使用单元格的值而不是单元格引用。我想知道如何使用单元格引用:
[在运行VBA时让公式说[=IF(B2>0,2,A2)]
而不是[=IF(1>0,2,1]
在C2单元格的Excel工作表中。]
Dim c As Range
Dim a As Integer
Dim b As Integer
'//loop it in column C
For Each c In Range(Range("C2"), Range("C2").End(xlDown))
a = c.Offset(0, -1) '// Column B
b = c.Offset(0, -2) '// Column A
c.Formula = "=IF(" & b & ">0,2," & a & ")" '// same format as formula [=IF(B2>0,2,A2)]
Next
如果我正确理解:
Dim a As Range
Dim b As Range
Set b = c.Offset(0, -1) '// Column B
Set a = c.Offset(0, -2) '// Column A
c.Formula = "=IF(" & b.Address(False,False) & ">0,2," & a.Address(False,False) & ")"
但是您无需循环或使用Address
;即可完成此操作。当公式在列中填充时,Excel将更新相对引用。
With ActiveSheet
Dim lastRow As Long
lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
.Range("C2:C" & lastRow).Formula = "=IF(B2>0,2,A2)"
End With
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句