比较2个日期时,我始终收到“运行时错误'13':类型不匹配”错误。该代码从第二个工作簿中获取日期,在这种情况下,我尝试将其粘贴到单元格中以确保它是一个日期。然后,它尝试将其与当前工作簿中已有的日期进行比较。粘贴日期和其他日期是相同的格式。我不知道为什么它不能比较两个日期!我也尝试过将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)
找不到in的值,则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
在in列中搜索Sheet1
cell中的值Sheet1!E5
。然后它将放入05/08/2016
找到的行的第五列。
With...End With
:https : //msdn.microsoft.com/en-us/library/wc500chb.aspx
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句