简体   繁体   中英

VBA Run-Time Error 1004 on ActiveCell.FormulaR1C1

The formula in Excel cells "=DATEVALUE(IF(ISERROR(INT(LEFT(MID(D2,FIND("/",D2)+1,LEN(D2)),FIND("/",MID(D2,FIND("/",D2)+1,LEN(D2)))-1))),DAY(D2),INT(LEFT(MID(D2,FIND("/",D2)+1,LEN(D2)),FIND("/",MID(D2,FIND("/",D2)+1,LEN(D2)))-1)))&"/"&IF(MID(D2,LEN(D2)-4,1)="/",INT(LEFT(D2,FIND("/",D2)-1)),MONTH(D2))&"/"&IF(MID(D2,LEN(D2)-4,1)="/",INT(RIGHT(D2,4)),YEAR(D2)))" works perfectly fine.

The below VBA code is auto generated using "Record-Macro" option in Excel 2007, to derive the above formula pragmatically.

However while running the VBA same code I get Run-time Error '1004'. Please help to get this rectified. VBA Code:

Sub Macro()

' Macro2 Macro

    Range("C2").Select
    ActiveCell.FormulaR1C1 = _
        "=DATEVALUE(IF(ISERROR(INT(LEFT(MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])),FIND(""/"",MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])))-1))),DAY(RC[1]),INT(LEFT(MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])),FIND(""/"",MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])))-1)))&""/""&IF(MID(RC[1],LEN(RC[1])-4,1)=""/"",INT(LEFT(RC[1],FIND(""/"",RC[1])-1)),MONTH(RC[1]))&""/""&IF(MID(RC[1],LEN(" & _
        ",1)=""/"",INT(RIGHT(RC[1],4)),YEAR(RC[1])))"
    Selection.AutoFill Destination:=Range("C2:C3239")
    Range("C2:C3239").Select

End Sub

You have lost the last D2)-4 part of the formula when you put it into VBA, thus making the formula invalid.

Sub Macro()

' Macro2 Macro

Range("C2").Select
ActiveCell.FormulaR1C1 = _
    "=DATEVALUE(IF(ISERROR(INT(LEFT(MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])),FIND(""/"",MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])))-1))),DAY(RC[1]),INT(LEFT(MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])),FIND(""/"",MID(RC[1],FIND(""/"",RC[1])+1,LEN(RC[1])))-1)))&""/""&IF(MID(RC[1],LEN(RC[1])-4,1)=""/"",INT(LEFT(RC[1],FIND(""/"",RC[1])-1)),MONTH(RC[1]))&""/""&IF(MID(RC[1],LEN(" & _
    "RC[1])-4,1)=""/"",INT(RIGHT(RC[1],4)),YEAR(RC[1])))"
Selection.AutoFill Destination:=Range("C2:C3239")
Range("C2:C3239").Select
End Sub

FWIW, I worked out the error by recording a macro while inserting the formula that you said worked in Excel, and then visually comparing that macro to the one you were using. It was fairly obvious where the difference lay as it was the very beginning of the second statement continuation line.

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