繁体   English   中英

我得到运行时错误'13':输入不匹配

[英]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需要一个数字,但事实上,从字符串中减去一个字符串,这会导致抛出异常。

如果ab是保持像“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) * 24c = Abs(b - a) * 24相同的问题。 Format函数的输出是文本,因此ab现在都是时间的文本表示。 你需要将它们转换回代表时间的双精度数c = Abs(TimeValue(b) - TimeValue(a)) * 24

你没有提供太多的细节。 可能有更好的方法来做到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM