2015-08-17 108 views
0

我想用VBA來查找兩列之間的時間差。我已經檢查過,兩列有相同的數據類型,但是每當我運行宏時,它總是給我類型不匹配的錯誤。我無法弄清楚爲什麼如此任何幫助將不勝感激。類型不匹配錯誤VBA

Sub timeshfiter() 
    lastrow = Application.CountA(Range("A:A")) 
    For i = 2 To lastrow 
    If (Worksheets("Sheet1").Cells(i, "A").Value = Worksheets("Sheet2").Cells(i,"A").Value) Then 
     If ((Abs(Worksheets("Sheet1").Cells(i, "I").Value - Worksheets("Sheet2").Cells(i, "I").Value) * 86400) <= TimeValue(20)) Then 
    Worksheets("Sheet1").Cells(i, "K").Value = Worksheets("Sheet2").Cells(i, "I").Value 
    Else: Worksheets("Sheet1").Cells(i, "K").Value = "Check" 
     End If 
    End If 

    Next i 

    End Sub 

回答

1

我發現了主要錯誤。條件行中使用TimeValue(20)。這會導致Type mismatch錯誤。

這裏,參考文獻(1)(2)使用TimeValue方法。

這裏是你的代碼的有效使用的樣本:

Sub timeshfiter() 

    lastrow = Application.CountA(Range("A:A")) 

    For i = 2 To lastrow 

     If Worksheets("Sheet1").Cells(i, "A").Value = Worksheets("Sheet2").Cells(i, "A").Value Then 

      If (Abs(Worksheets("Sheet1").Cells(i, "I").Value - Worksheets("Sheet2").Cells(i, "I").Value) * 86400) <= TimeValue("00:20:00 AM") Then 
                                  '^ valid time value "00:20:00 AM"   
       Worksheets("Sheet1").Cells(i, "K").Value = Worksheets("Sheet2").Cells(i, "I").Value 

      Else 

       Worksheets("Sheet1").Cells(i, "K").Value = "Check" 

      End If 

     End If 

    Next i 

End Sub