运行-时间错误13

Run-Time Error 13

在编程方面过得并不愉快。我不明白为什么 VBA 不能做下面的总和。

你能帮忙吗。

我在用户表单中有 2 个字段都带有日期。我只想减去它们来计算中间的天数

我试过这两种变体。

ws1.Cells(mRow, 28).Value = TxtRecDate.Value - TxtDOD.Value
ws1.Cells(mRow, 28).Value = CInt(TxtRecDate.Value) - CInt(TxtDOD.Value)

两者都给我 运行-时间错误 13 不匹配。

你能帮忙吗?

谢谢,

您需要将文本框中的 text 转换为 date:

    ws1.Cells(mRow, 28).Value = DateValue(TxtRecDate.Value) - DateValue(TxtDOD.Value)

请注意,如果文本未正确表示日期,这将导致 Runtime Error 13: Type Mismatch。您可以通过首先测试文本框值来处理此问题:

    If IsDate(TxtRecDate) And IsDate(TxtDOD) Then
        ws1.Cells(mRow, 28).Value = DateValue(TxtRecDate.Value) - DateValue(TxtDOD.Value)
    Else
        MsgBox "Invalid dates entered", vbExclamation + vbOKOnly
    End If

您应该测试两个文本框是否包含有效日期。然后使用 DateValue 将字符串值转换为日期值。

If IsDate(TxtRecDate.Value) And IsDate(TxtDOD.Value) Then

    ws1.Cells(mRow, 28).Value = DateValue(TxtRecDate.Value) - DateValue(TxtDOD.Value)

End If