简体   繁体   中英

I am getting Run-Time Error '13': Type Mismatch

I am having problems with my syntax below. I keep on getting Run Time error. Please advise.

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`

Your prompt response is much appreciated! Thanks!

Judging by the code posted, time is being compared.

The problem arises because Abs expects a number, but in fact, a string is subtracted from a string, which causes an exception to throw.

If a and b are string variables holding values like "16:00" that are later formatted into "4:00", I suggest implementing a function to calculate the time in minutes, and then their difference.

Here is the function:

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

Then, the code will look like

a = Trim(Format(txtStart.Text, "hh:mm AMPM"))
b = Trim(Format(txtEnd.Text, "hh:mm AMPM"))
C = Abs(ConvertToMinutes(b) - ConvertToMinutes(a)) * 24

Please adjust the calculations so that you get the required result.

You cannot throw text that looks like a date, time or datetime into the Format function without converting them to real dates.

  a = Format(CDate(txtStart.Text), "hh:mm AMPM")
  b = Format(CDate(txtEnd.Text), "hh:mm AMPM")

You could also use TimeValue for the time. The DateValue function will only see the date portion of the text string. CDate sees both the date and time.

Addendum:

You will have the same problem with c = Abs(b - a) * 24 . The output of the Format function is text so both a & b will now be text representations of time. You need to convert them back to doubles representing time with c = Abs(TimeValue(b) - TimeValue(a)) * 24 .

You haven't provided much in the way of detail. There is probably a better way to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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