使用VBA脚本将2个时间variables分配给2个单元格中的时间值抛出types不匹配错误13

我试图将系统时间与存储在相邻列中的开始和结束时间进行比较。 下面的代码工作得很好,直到我改变了一些代码(但恢复到旧的代码,因为它不工作)。 在恢复到旧代码后,比较不起作用,并抛出“types不匹配”错误“13”。 另外,For循环之后的'z'的值变成了0,因为它没有得到正确的输出。

任何帮助是极大的赞赏。

Sub MyBtn_Click() Dim i As Integer Dim w As Integer Dim z As Integer Dim tm1 As Date Dim tm2 As Date Dim tm3 As Date tm1 = Time w = Weekday(Date, vbSunday) w = w + 2 For i = 2 To 32 tm2 = TimeValue(Cells(i, 1).Text) ' this is the line throwing 'type mismatch' tm3 = TimeValue(Cells(i, 2).Text) If tm1 >= tm2 And tm1 <= tm3 Then z = i Exit For End If Next i myMsgBox i ' here i = 32, don't know why myMsgBox z ' z = 0 for some reason MsgBox Cells(z, w), vbOKOnly, "Result" ' does not give the cell contents as z=0 End Sub 

这个逻辑做了诀窍 –

 If IsDate(Cells(i, 1).Value) And IsDate(Cells(i, 2).Value) Then 

…但是,当z变成0时,我得到了一个运行时错误。所以我只是尝试使用.Text(把它重新放回),而不是.Value,现在程序正在工作!

所以这就是它的样子 –

 For i = 2 To 32 If IsDate(Cells(i, 1).Text) And IsDate(Cells(i, 2).Text) Then time2 = TimeValue(Cells(i, 1).Text) time3 = TimeValue(Cells(i, 2).Text) If tm1 >= time2 And tm1 <= time3 Then z = i Exit For End If End If Next i 

您需要确保单元格中的值可以转换为时间。 如果没有,你会得到不匹配的消息。 另外我总是使用.value而不是.text

 'declare as dates to ensure that the values are treated as dates and not as something else dim tm1 as Date, tm2 as Date, tm3 as Date For i = 2 To 32 'test to make sure the cells have date/time values If IsDate(Cells(i, 1).Value) And IsDate(Cells(i, 2).Value) Then tm2 = TimeValue(Cells(i, 1).Value) tm3 = TimeValue(Cells(i, 2).Value) If tm1 >= tm2 And tm1 <= tm3 Then Z = i Exit For End If End If Next i 

您需要使用F8慢慢地遍历代码,并检查每个步骤中variables的值,以确定代码是否正常工作。 此代码将避免MisMatch错误,但您将需要检查数据,以确保它以您想要的方式工作。

至于你的第二个问题:我= 32,因为这是在循环中设置的最后一个值。

而z = 0,因为条件从来没有满足你的if语句: If tm1 >= tm2 And tm1 <= tm3 Then