smcamero
smcamero

Reputation: 27

Runtime Error 13 Type Mismatch when passing a userform textbox value to a function

I have a userform with textboxes, and some of those are supposed to contain integers. I found somewhere on the internet (I think on this site) this IsInteger function which I have stored in a module just for functions:

Function IsInteger()
If IsNumeric(testsubject) Then
    If testsubject - Int(testsubject) <> 0 Then
        integerYes = True
    Else: integerYes = False
    End If
End If
End Function

The following code block relates to one of the userform textboxes:

  Private Sub IB_LoanTermYears_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    'Data validation
        If Me.IB_LoanTermYears.Value = "" Then
        ElseIf IsNumeric(Me.IB_LoanTermYears.Value) = False Then
            blahAnswer = MsgBox("Please enter a valid number.", , "Invalid Entry")
            Me.IB_LoanTermYears.SetFocus
        ElseIf IsInteger(Me.IB_LoanTermYears.Value) = False Then
            blahAnswer = MsgBox("Please enter a whole number.", , "Invalid Entry")
            Me.IB_LoanTermYears.SetFocus
        ElseIf Me.IB_LoanTermYears.Value < 0 Then
            blahanswer MsgBox("Please enter a positive number.", , "Invalid Entry")
            Me.IB_LoanTermYears.SetFocus
        End If
    End Sub

When I exit the textbox, I get a runtime error 13 with ElseIf IsInteger(Me.IB_LoanTermYears.Value) = False Then highlighted. What gives? I saw a very similar post that concluded that other empty textboxes were messing things up, but I don't see how that can affect this textbox as they're not linked in any way except that they're in the same userform.

Thanks!

Upvotes: 0

Views: 571

Answers (2)

Vityata
Vityata

Reputation: 43585

The error appears because the function does not take arguments. This is a better way to use the Integer funciton, which would actually check, whether the parsed variant could be converted to Long without a loss. E.g.: Clng(43.4) would return 43, thus a loss appears:

Function ParseToLong(testSubject As Variant) As Boolean

    If IsNumeric(testSubject) Then
        If testSubject - CLng(testSubject) = 0 Then
            ParseToInteger = True
            Exit Function
        End If
    End If

    ParseToInteger = False

End Function

Just keep in mind, that ParseToLong("32") would return True, as far as the string "32" could be converted to numeric 32.

Upvotes: 0

Scott Craner
Scott Craner

Reputation: 152505

Make sure the Fuction accepts inputs and the output is Boolean.

Since the default of a Boolean is FALSE we only need to change to True

Function IsInteger(testsubject As Variant) As Boolean
If IsNumeric(testsubject) Then
    IsInteger = (testsubject - CInt(testsubject) = 0)
End If
End Function

Upvotes: 2

Related Questions