2016-08-05 85 views
0

比較2個日期時,我總是收到「運行時錯誤13」:類型不匹配「錯誤。代碼從第二個工作簿中獲取日期,在這種情況下,我試圖將它粘貼到單元格中以確保它是一個日期......它是什麼。然後它會嘗試將其與當前工作簿上的日期進行比較。粘貼的日期和其他日期是相同的格式。我不知道爲什麼它不能比較兩個日期!我也嘗試將CDate()放在每個組件周圍都無濟於事。請幫忙。運行時間錯誤'13:比較日期時類型不匹配 - EXCEL VBA

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

請檢查這兩個日期是'則IsDate()'是真的......可能有至少一個日期時像一個字符串處理的機會......請參閱[這] (http://stackoverflow.com/questions/10502802/cdate-type-mismatch-error) –

+2

不會'單元格(5,5)=範圍(「A:A」)'比較單個單元格到整體柱? 'Cells(5,5)= Range(「A1」)'起作用。 –

+0

@ DarrenBartrup-Cook多數民衆贊成在一個:)把它寫出 –

回答

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 

它將Sheet1搜索欄A爲單元格Sheet1!E5中的值。然後它會將05/08/2016放在找到的行的第5列。

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

+0

非常感謝Darren!這工作完美。我非常感謝! – dReDone

相關問題