문제

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.

도움이 되었습니까?

해결책

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).

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top