复制 Excel 到 VBA 中的单元格公式

Replicating Cell formula in Excel through VBA

我想在 VBA 内的 C 列中创建 IF 公式。但是,当我这样做时,公式显示为使用单元格的值而不是单元格引用。我想知道如何使用单元格引用:

[当 VBA 为 运行 时,在单元格 C2 的 excel sheet 中使用公式 [=IF(B2>0,2,A2)] 而不是 [=IF(1>0,2,1] .]

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