运行时错误'13:比较日期 - EXCEL VBA时输入不匹配

时间:2016-08-05 12:10:36

标签: excel vba types mismatch

比较2个日期时,我一直收到“运行时错误'13':输入错误”错误。代码从第二个工作簿中获取日期,在这种情况下,我试图将其粘贴到单元格中以确保它是一个日期......它是什么。然后它尝试将它与当前工作簿上已有的日期进行比较。粘贴日期和其他日期是相同的格式。我不知道为什么它不能比较2个日期!我也试过在每个组件周围放置CDate()无济于事。请帮忙。

Sub NewMacro()
Dim CurrentWB As Workbook
Dim ForecastWB As Workbook
Dim strDate As Date

Set CurrentWB = ActiveWorkbook

Application.DisplayAlerts = False
Set ForecastWB = Workbooks.Open("My Other Workbook File Name")
Application.DisplayAlerts = True
strDate = ActiveWorkbook.Worksheets("My Sheet Name").Cells(20, "N").Value

ThisWorkbook.Activate

If Cells(5, 5) = Range("A:A") Then 'TYPE MISMATCH HERE
    Set x = Range("A:A").Find(what:=Cells(5, 5), lookat:=xlWhole)
    Cells(x, 5) = strDate
End If

End Sub

1 个答案:

答案 0 :(得分:3)

从我在你的代码中读到的内容: Cells(5, 5) = Range("A:A") - 您无法将单个值与整列值进行比较。

Cells(x, 5) = strDate - x是范围对象,而不是行号。请改用x.Row

如果找不到Cells(5,5)中的值,则x将等于nothing,导致此行出错:Cells(x, 5) = strDate

尝试调整此代码:

Sub Test()

    Dim x As Range

    With ThisWorkbook.Worksheets("Sheet1")
        Set x = .Range("A:A").Find(What:=.Cells(5, 5), LookIn:=xlValues, LookAt:=xlWhole)
        If Not x Is Nothing Then
            .Cells(x.Row, 5) = CDate("5 Aug 2016")
        End If
    End With

End Sub

它会在A中的Sheet1列中搜索单元格Sheet1!E5中的值。然后,它会将05/08/2016放在它找到的行的第五列中。

With...End Withhttps://msdn.microsoft.com/en-us/library/wc500chb.aspx