Domanda

I cannot understand why this is working:

Function ToNumber(ByVal sVal As String) As Double
sVal = Replace(sVal, ",", ".")
If IsNumeric(sVal) Then
    ToNumber = CDbl(sVal)
Else
    ToNumber = 0
End If
End Function

while this one does not (I am getting a type mismatch):

Function ToNumber(ByVal sVal As String) As Double
sVal = Replace(sVal, ",", ".")
ToNumber = IIf(IsNumeric(sVal), CDbl(sVal), 0)
End Function

formally they should be equivalent. thank you.

È stato utile?

Soluzione

Unfortunately VBA will evaluate both arguments in the Iif. In your case CDbl(sVal) gives you a type mismatch since it will be evaluated even if IsNumeric(sVal) is False.

Your best bet is to retain the If, Else, End If construct. Or, you could do this (retaining the comments since the code is complex):

Function ToNumber(ByVal sVal As String) As Double
    'note that (1) the error handling is reset to that in the caller
    '              when the function exits.
    '          (2) ToNumber is zero by default
    On Error Resume Next 
    ToNumber = CDbl(Replace(sVal, ",", "."))
End Function

(This is unlike the ternary in Java, C and C++ where exactly one of the expressions are evaluated).

Altri suggerimenti

In the statement IIf(IsNumeric(sVal), CDbl(sVal), 0), CDbl(sVal) is evaluated regardless of the result of IsNumeric and causes type mismatch the run time error.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top