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