![](/img/trans.png)
[英]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.