简体   繁体   中英

Excel VBA Formula - 1004 object or application defined error

I'm adding a macro to allow the user to change the formula in a cell. Here is the code that added to a module:

Sub OverrideCharge()

title = "Override Total Labor Cost"

'Ask user if they want to override
overrideMsg = MsgBox("Override Total Labor Cost with 4-Hour Minimum Charge?", vbYesNo, title)
If overrideMsg = vbYes Then
    Sheets("Totals").Activate
    Range("L25").Formula = "=SUM(IF(MOD(ROW(INDIRECT(""L11:L""&ROW()-1)),2)=1,INDIRECT(""L11:L""&ROW()-1),0)))"
Else: overrideMsg = vbNo
    Exit Sub
End If

End Sub

I get the error when defining the Range("L25").Formula . I don't know if it's a syntax error or if I'm referencing the sheet/cell incorrectly.

您需要对引号和括号进行排序,应为:

Range("L25").Formula = "=SUM(IF(MOD(ROW(INDIRECT(""L11:L""&(ROW()-1))),2)=1,INDIRECT(""L11:L""&(ROW()-1)),0))"

When working with long complex formulas I like adding a FormulaString variable to help me debug (this way I can see better where the error is coming from).

Also, there is no need to Activate the Sheets("Totals") , and then placing the formula in Cell L25, you can do it directly with Sheets("Totals").Range("L25").Formula .

My own preference, instead of starting to count how many " , or "" , or maybe """" I need, I like working with Chr(34) .

Code

Sub OverrideCharge()

Dim FormStr As String
Title = "Override Total Labor Cost"

'Ask user if they want to override
overrideMsg = MsgBox("Override Total Labor Cost with 4-Hour Minimum Charge?", vbYesNo, Title)
If overrideMsg = vbYes Then
    ' use a String for Formula to help debug it (before trying to put it inside a cell)
    FormStr = "=SUM(IF(MOD(ROW(INDIRECT(" & Chr(34) & "L11:L" & Chr(34) & "&ROW()-1)),2)=1,INDIRECT(" & Chr(34) & "L11:L" & Chr(34) & "&ROW()-1),0))"
    Debug.Print FormStr '<-- for debug only
    Sheets("Totals").Range("L25").Formula = FormStr
Else
    overrideMsg = vbNo
    Exit Sub
End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM