如何使用VBA将公式实现到Excel单元格中

时间:2016-10-26 05:01:13

标签: excel vba excel-vba excel-formula

我想在Excel单元格中实现以下公式

IF(OR(D12>0,C13=""),"",MAX(SUM($C$12:C13)-$D$9,0))

(一旦应用公式,我应该得到以下结果(手动实施公式):

enter image description here

所以我写了如下的简单宏,但无法实现公式,公式将值返回为“true”

Sub adjustoldbills()

lastRow_sht4 = Sheet4.Range("A" & Rows.Count).End(xlUp).Row
Sheet4.Cells(12, 11) = ""

For i = 1 To lastRow_sht4 - 10
    If Sheet4.Cells(11 + i, 1) <> "" Then
        '=MAX(SUM($C$12:C15)-$D$9,0)
        Sheet4.Cells(12, 4).Formula = "=MAX(SUM($C$12:C" & 12 & ")-$D$9,0)"
        Sheet4.Cells(11 + i, 4).Formula = "=(if(or(D" & 11 + i > 0 & ",C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & "," & "MAX(SUM($C$12:C" & 12 & i & ")-$D$9,0)"
    End If
Next i

End Sub

我在通过vba宏实现公式后得到了错误的结果,如下图所示:

enter image description here

如何实现公式并获得预期的价值。

2 个答案:

答案 0 :(得分:-1)

尝试将长公式转换为VBA时,请尝试使用String变量来帮助您对其进行测试。

 Dim FormulaStr              As String

 FormulaStr = "=IF(OR(D" & 11 + i & ">0,C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & _
      Chr(34) & Chr(34) & ",MAX(SUM($C$12:C" & 12 + i & ")-$D$9,0))"
 Debug.Print FormulaStr

然后,在即时窗口中,您将获得:

=IF(OR(D12>0,C13=""),"",MAX(SUM($C$12:C13)-$D$9,0))

这是您要转换为VBA的公式。

现在您需要做的就是添加以下行:

 Sheet4.Cells(11 + i, 4).Formula = FormulaStr

如果要跳过String变量,只需替换

行即可
Sheet4.Cells(11 + i, 4).Formula = "=(if(or(D" & 11 + i > 0 & ",C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & "," & "MAX(SUM($C$12:C" & 12 & i & ")-$D$9,0)"

为:

Sheet4.Cells(11 + i, 4).Formula = "=IF(OR(D" & 11 + i & ">0,C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & ",MAX(SUM($C$12:C" & 12 + i & ")-$D$9,0))"

答案 1 :(得分:-1)

我会采用另一种方式,没有循环并利用Range对象的SpecialCells()方法

Option Explicit

Sub adjustoldbills()

    With Sheet4
        .Range("D12").FormulaR1C1 = "=MAX(RC[-1]-R9C4,0)" 
        With .Range("A13", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
            With .Offset(, 2).SpecialCells(xlCellTypeConstants)
                .Offset(, 1).FormulaR1C1 = "=IF(R[-1]C>0,"""",MAX(SUM(R12C[-1]:RC[-1])-R9C4,0))"
                With .Areas(.Areas.Count)
                    .Offset(, 1).Cells(.Rows.Count).Offset(1).FormulaR1C1 = "=IF(R[-1]C>0,"""",MAX(SUM(R12C[-1]:RC[-1])-R9C4,0))"
                End With
            End With
        End With
    End With
End Sub