比较VBA中的时间值抛出运行时错误13'types不匹配'

我试图将系统时间与存储在两个相邻单元中的时间进行比较。 我尝试了下面的时间比较,它只是正常工作…

* 此代码工作正常 * Sub btn_Click()

MsgBox Range("C4"), vbOKOnly, "Test" Dim time1 As Date Dim time2 As Date time1 = Time time2 = TimeValue(Cells(3, 1).Text) If time1 < time2 Then MsgBox str, vbOKOnly, "MsgIf" Else MsgBox str1, vbOKOnly, "MsgElse" End If 

结束小组


但这是行不通的! If条件抛出错误说'types不匹配'。 请帮忙!!!

 Dim i As Integer Dim w As Integer Dim tm1 As Date Dim tm2 As Date Dim tm3 As Date tm1 = Time For i = 2 To 31 tm2 = TimeValue(Cells(i, 1).Text) tm3 = TimeValue(Cells(i, 2).Text) If tm1 > tm2 & tm1 < tm3 Then ' this is the line that throws 'type mismatch' error Exit For End If Next i MsgBox Cells(i, w), vbOKOnly, "Test" 

为了这个目的,我会把答案(在评论中)作为答案(而不是评论)。 @Simoco或@Enderland,随意做同样的事情,我会删除我的答案。

VBA不使用&运算符,也不使用| 。 相反,它分别使用AndOr

这里是:

VBA不使用&运算符,也不使用| 。 相反,它分别使用AndOr

改变这一点

 If tm1 > tm2 & tm1 < tm3 Then 

对此

 If tm1 > tm2 And tm1 < tm3 Then 

解决了Type Mismatch Error
谢谢@simoco和@enderland