[英]Why am I getting (run-time error '13': ) type mismatch when looping across a (sometimes-empty) variant?
[英]I am getting Run-Time Error '13': Type Mismatch
我的语法问题如下。 我一直在收到运行时错误。 请指教。
Dim a As Date Dim b As Date Dim c As Double
If Val(txtStart.Text) = Null Or Val(txtEnd.Text) = Null Then
Cells(eRow, 6).Value = txtEffort.Value
Else
a = Format(txtStart.Text, "hh:mm AMPM")
b = Format(txtEnd.Text, "hh:mm AMPM")
c = Abs(b - a) * 24
Cells(eRow, 6).Value = c
End If`
非常感谢您的快速回复! 谢谢!
根据发布的代码判断,时间正在进行比较。
问题出现是因为Abs
需要一个数字,但事实上,从字符串中减去一个字符串,这会导致抛出异常。
如果a
和b
是保持像“16:00”之类的值的字符串变量,后来被格式化为“4:00”,我建议实现一个函数来计算以分钟为单位的时间,然后计算它们之间的差异。
这是功能:
Function ConvertToMinutes(ByVal time_str As String) As Integer
ConvertToMinutes = 0
On Error GoTo Ende
splts = Split(time_str, ":")
ConvertToMinutes = CInt(splts(0)) * 60 + CInt(splts(1))
Ende:
On Error GoTo 0
End Function
然后,代码看起来像
a = Trim(Format(txtStart.Text, "hh:mm AMPM"))
b = Trim(Format(txtEnd.Text, "hh:mm AMPM"))
C = Abs(ConvertToMinutes(b) - ConvertToMinutes(a)) * 24
请调整计算,以便获得所需的结果。
您不能将看起来像日期,时间或日期时间的文本放入Format
函数,而不将它们转换为实际日期。
a = Format(CDate(txtStart.Text), "hh:mm AMPM")
b = Format(CDate(txtEnd.Text), "hh:mm AMPM")
您还可以使用TimeValue
。 DateValue
函数只能看到文本字符串的日期部分。 CDate
看到了日期和时间。
附录:
你会c = Abs(b - a) * 24
与c = Abs(b - a) * 24
相同的问题。 Format
函数的输出是文本,因此a & b现在都是时间的文本表示。 你需要将它们转换回代表时间的双精度数c = Abs(TimeValue(b) - TimeValue(a)) * 24
。
你没有提供太多的细节。 可能有更好的方法来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.