Search code examples
vbaexcelexcel-2013

FormulaR1C1 including variable - Application-Defined Error: Excel VBA


I am attempting to do a calculation in Excel VBA but I get the error

Application-Defined or Object-Defined Error

This is the code I am attempting to execute. The error happens on the line .FormulaR1C1 = ..., but I'm not sure why.

Function CalcNumDays()
Dim d1 As Date, d2 As Date, NoofDays As Variant
d1 = "01/01/2017"
d2 = "03/01/2017"

NoofDays = Application.WorksheetFunction.NetworkDays(d1, d2)

With Sheets("ALL")
    With .Range("K2:K" & .Cells(.Rows.Count, "A").End(xlUp).Row)
        .FormulaR1C1 = "=IFERROR(SUM((RC[-8]+RC[-7]/RC[-4])*NoofDays,0)"
        .Value = .Value
    End With
End With

End Function

Sample Data


Solution

  • try this

    .FormulaR1C1 = "=IFERROR(SUM(RC[-8]+RC[-7]/RC[-4])*" & NoofDays & ",0)"