键入不匹配错误VBA

时间:2015-08-17 06:28:52

标签: excel-vba runtime vba excel

我正在尝试使用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 个答案:

答案 0 :(得分:1)

我发现了主要错误。您在条件行中使用TimeValue(20)。这导致Type mismatch错误。

此处,使用 TimeValue 方法参考(1) (2)

以下是与您的代码有效使用的示例:

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