我在下面的语法上有问题。我一直收到运行时错误。请给我建议。
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`非常感谢您的及时回复!谢谢!
发布于 2015-02-18 18:09:01
从发布的代码来判断,时间是比较的。
之所以出现这个问题,是因为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请调整计算,以获得所需的结果。
发布于 2015-02-18 18:11:39
您不能将看起来像日期、时间或日期时间的文本抛入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,您也会遇到同样的问题。Format函数的输出是文本,因此a&b现在都是时间的文本表示。您需要使用c = Abs(TimeValue(b) - TimeValue(a)) * 24将它们转换回表示时间的双精度数。
你没有提供太多的细节。也许有一种更好的方法可以做到这一点。
https://stackoverflow.com/questions/28580104
复制相似问题