Search code examples
excelvbafunctionruntime-erroruserform

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!


Solution

  • 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