You can often get around Type Mismatch errors by using Is Functions. For example here is a code that asks the user his age. Since we don't have any control over what the user types in, we need to varify that he actually typed in a number:
Dim lngAge
lngAge = InputBox("Please enter your age in years")
If IsNumeric(lngAge) Then
lngAge = CLng(lngAge)
lngAge = lngAge + 50
MsgBox "In 50 years, you will be " & CStr(lngAge) & " years old."
Else
MsgBox "Sorry, but you did not enter a valid number."
End If
Notice how we use the IsNumeric ( ) function to test whether or not the user actually entered a valid number. Since we're palnning to use the CLng ( ) function to coerce the subtype, we want to avoid a Type Mismatch error. What we have not stated explicitly is that the subtype of the variable does not have to be numeric in order for IsNumeric ( ) to return true. IsNumeric ( ) examines the actual value of the variable, rather than its subtype. The subtype of the variable and the value of the variable are two different things. The behavior is actually what allows us to use IsNumeric ( ) to avoid a Type Mismatch error. If IsNumeric ( ) examined the subtype, it would not work as we have been using it. In line three of the above example, the subtype of the lngAge variable is String, yet IsNumeric ( ) returns True if the variable has a number in it. That is because IsNumeric ( ) is considering the value of lngAge, not the subtype. We can test the value before trying to convert the variable's subtype to a different subtype. The function IsDate ( ) works in exactly the same way.
First
Next