Isnumber在Excel VBA中将错误定义为对象定义错误

时间:2018-08-21 01:24:02

标签: excel vba excel-vba

当我尝试在vba中使用该公式时,我在列中有两种不同的日期格式,它给出了应用程序定义的对象错误..

Ex:日期格式

9/5/2018 17:51 ==> 2018年5月9日

17/07/2018 15:45:20 ==>这是2018年7月17日

公式:

=IF(ISNUMBER(DAY(N2)),DAY(N2),MID(N2,FIND("/",N2,1)+1,FIND("/20",N2,1)-4))&"/"&IF(ISNUMBER(MONTH(N2)),MONTH(N2),MID(N2,1,FIND("/",N2,1)-1))&"/"&IF(ISNUMBER(N2),YEAR(N2),MID(N2,FIND("/20",N2,1)+1,4))


Sub test()
Dim LastRow As Long
LastRow = ActiveSheet.Range("D" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow

           ActiveSheet.Range(i, 2).Formula = " If(ISNUMBER (DAY(Range(""D"" & i))),DAY(Range(""D"" & i)),MID(Range(""D"" & i),FIND(""/"",Range(""D"" & i),1)+1,FIND(""/20"",Range(""D"" & i),1)-4))&""/""&IF(ISNUMBER(MONTH(Range(""D"" & i))),MONTH(Range(""D"" & i)),MID(Range(""D"" & i),1,FIND(""/"",Range(""D"" & i),1)-1))&""/""&IF(ISNUMBER(Range(""D"" & i)),YEAR(Range(""D"" & i)),MID(Range(""D"" & i),FIND(""/20"",Range(""D"" & i),1)+1,4))"
Next i
End Sub

1 个答案:

答案 0 :(得分:0)

  1. 从公式中删除Range( ... ...DAY(Range(""D"" & i))...
  2. 您还缺少=符号... "=If(ISNUMBER (DAY...

其他人已经给您一些建议。让我解释一下您为什么遇到此Application - defined object错误。

您的公式

=IF(ISNUMBER(DAY(N2)),DAY(N2),MID(N2,FIND("/",N2,1)+1,FIND("/20",N2,1)-4))&"/"&IF(ISNUMBER(MONTH(N2)),MONTH(N2),MID(N2,1,FIND("/",N2,1)-1))&"/"&IF(ISNUMBER(N2),YEAR(N2),MID(N2,FIND("/20",N2,1)+1,4))

可以写成(在VBA中)

"=IF(ISNUMBER(DAY(N" & "2" & _
")),DAY(N" & "2" & _
"),MID(N" & "2" & _
",FIND(""/"",N" & "2" & _
",1)+1,FIND(""/20"",N" & "2" & _
",1)-4))&""/""&IF(ISNUMBER(MONTH(N" & "2" & _
")),MONTH(N" & "2" & _
"),MID(N" & "2" & _
",1,FIND(""/"",N" & "2" & _
",1)-1))&""/""&IF(ISNUMBER(N" & "2" & _
"),YEAR(N" & "2" & _
"),MID(N" & "2" & _
",FIND(""/20"",N" & "2" & _
",1)+1,4))

可以进一步适应

"=IF(ISNUMBER(DAY(N" & i & _
")),DAY(N" & i & _
"),MID(N" & i & _
",FIND(""/"",N" & i & _
",1)+1,FIND(""/20"",N" & i & _
",1)-4))&""/""&IF(ISNUMBER(MONTH(N" & i & _
")),MONTH(N" & i & _
"),MID(N" & i & _
",1,FIND(""/"",N" & i & _
",1)-1))&""/""&IF(ISNUMBER(N" & i & _
"),YEAR(N" & i & _
"),MID(N" & i & _
",FIND(""/20"",N" & i & _
",1)+1,4))

所以您看到我们在公式中不需要Range()。现在您可以在循环中使用它了。

话虽如此,不需要使用循环。您可以一次输入一个范围内的公式。看到这个例子

Sub test()
    Dim LastRow As Long
    Dim ws As Worksheet
    Dim sFormula As String

    '~~> Change this to the relevant sheet
    '~~> Stop using `Activesheet`. Active sheet
    '~~> may not be the sheet you think is active
    Set ws = Sheet1

    sFormula = "=IF(ISNUMBER(DAY(N2)),DAY(N2),MID(N2,FIND(""/"",N2,1)" & _
               "+1,FIND(""/20"",N2,1)-4))&""/""&IF(ISNUMBER(MONTH(N2))," & _
               "MONTH(N2),MID(N2,1,FIND(""/"",N2,1)-1))&""/""&IF(" & _
               "ISNUMBER(N2),YEAR(N2),MID(N2,FIND(""/20"",N2,1)+1,4))"
    With ws
        LastRow = .Range("D" & .Rows.Count).End(xlUp).Row

        .Range("B2:B" & LastRow).Formula = sFormula
    End With
End Sub