运行 时间错误 '13:比较日期时类型不匹配 - EXCEL VBA
Run Time Error '13: Type Mismatch when comparing Dates - EXCEL VBA
我在比较两个日期时总是收到 "Run Time Error '13': Type Mismatch" 错误。该代码从第二个工作簿中获取一个日期,在本例中,我试图将其粘贴到一个单元格中以确保它是一个日期……它是什么。然后它会尝试将其与当前工作簿中已有的日期进行比较。粘贴的日期和其他日期是相同的格式。我不知道为什么它不能比较这两个日期!我也试过将 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
从你的代码中我可以读到:
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
它将在 Sheet1
中的列 A
中搜索单元格 Sheet1!E5
中的值。然后它将 05/08/2016
放在它找到的行的第五列中。
With...End With
:
https://msdn.microsoft.com/en-us/library/wc500chb.aspx
我在比较两个日期时总是收到 "Run Time Error '13': Type Mismatch" 错误。该代码从第二个工作簿中获取一个日期,在本例中,我试图将其粘贴到一个单元格中以确保它是一个日期……它是什么。然后它会尝试将其与当前工作簿中已有的日期进行比较。粘贴的日期和其他日期是相同的格式。我不知道为什么它不能比较这两个日期!我也试过将 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
从你的代码中我可以读到:
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
它将在 Sheet1
中的列 A
中搜索单元格 Sheet1!E5
中的值。然后它将 05/08/2016
放在它找到的行的第五列中。
With...End With
:
https://msdn.microsoft.com/en-us/library/wc500chb.aspx