运行时间错误'13:types不匹配比较date – EXCEL VBA
比较两个date时,我总是收到“运行时错误”13“types不匹配”错误。 代码从第二个工作簿抓取一个date,在这种情况下,我试图将它粘贴到一个单元格中,以确保它是一个date…这是什么。 然后尝试将其与当前工作簿上的date进行比较。 粘贴date和其他date是相同的格式。 我不知道为什么它不能比较两个date! 我也试过把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
。
如果没有findCells(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
中search单元Sheet1!E5
的值。 然后它会把05/08/2016
放在它find的那一行的第五列。
With...End With
: https : //msdn.microsoft.com/en-us/library/wc500chb.aspx