简体   繁体   English

如何使用VBA通过循环来循环DATEDIF公式?

[英]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. 我试图使用VBA循环DATEDIF公式,但我不断收到运行时错误'1004':应用程序定义的错误或对象定义的错误。 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 . 如果在公式中使用RC表示法,则需要使用FormulaR1C1 ,而不仅是Formula

Also, the d must be in double quotes, not single quotes. 同样, d必须用双引号引起,而不是单引号。 If you need to enter double quotes inside a VBA string, you need to double them. 如果您需要在VBA字符串中输入双引号,则需要将它们加倍。 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. 它在我的测试中有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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