运行时错误13

在编程方面没有太好的一天。 我不明白为什么VBA不能做以下的总和。

你能帮忙吗?

我有一个用户窗体中的两个字段都有一个date。 我想要的就是把它们减去,以计算出中间的日子

我已经尝试了2个变种。

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

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

你能帮忙吗?

谢谢,

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

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

注意这将导致Runtime Error 13: Type Mismatch如果文本不正确代表date。 你可以通过先testing文本框的值来处理这个问题:

  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 

您应该testing两个文本框是否包含有效的date。 然后使用DateValue将string值转换为date值。

 If IsDate(TxtRecDate.Value) And IsDate(TxtDOD.Value) Then ws1.Cells(mRow, 28).Value = DateValue(TxtRecDate.Value) - DateValue(TxtDOD.Value) End If