简体   繁体   中英

How to loop a DATEDIF formula through a loop using VBA?

I'm trying to loop a DATEDIF formula, using VBA, but I keep getting Run-time error '1004': Application-defined or object-defined error. I'm not sure why the code keeps kicking out. The formula itself works.

Sub DateandDaysFormula()


    With ThisWorkbook.Sheets("HDT Pivot Table")
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row

        .Range(.Range("L2"), .Range("L" & lastRow)).Formula = _
            "=DATEDIF(RC[-5],TODAY(),'d')"
        .Range(.Range("X2"), .Range("X" & lastRow)).Formula = _
            "=IFERROR(VLOOKUP(D2,DataDrop!A:C,2,FALSE),0)"
    End With

End Sub

If you use RC notation in a formula, you need to use FormulaR1C1 , not just Formula .

Also, the d must be in double quotes, not single quotes. If you need to enter double quotes inside a VBA string, you need to double them. So, the problematic line should work with this change:

.Range(.Range("L2"), .Range("L" & lastRow)).FormulaR1C1 = _
            "=DATEDIF(RC[-5],TODAY(),""d"")"

It works in my tests.

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