Search code examples
ms-accessvbams-access-2007

Trouble with InputBoxes


I'm currently working with InputBoxes in MS Access VBA. I'm examining validation and handling how the user interacts with the InputBox through pressing the OK or Cancel buttons.

Correct me if I'm wrong but InputBoxes can return any data type and by default return a string? For example:

Dim userInputValue As String

'Text to display, Title, Default Value
userInputValue = InputBox("Please enter a #", "Determine Limit", 10000)

If userInputValue = "" Then
    MsgBox ("You pressed the cancel button...")
End If

If the user presses the Cancel button this will run fine.

But when I swap this for an integer value like so:

Dim userInputValue As Integer
'Text to display, Title, Default Value
userInputValue = InputBox("Please enter a #", "Determine Limit", 10000)

If userInputValue = 0 Then
    MsgBox ("You pressed the cancel button...")
End If

I receive a Type Mismatch: Runtime Error '13' Why is this? When I debug the code and look at what is being returned I find that the userInputValue is actually 0, which is what I'm checking for. So is the problem that the InputBox is actually returning a string?


Solution

  • When in doubt, check the inbuilt VBA help ;)

    InputBox() returns a String

    You can try this for Integers

    Sub Sample()
        Dim Ret As String, userInputValue As Integer
    
        'Text to display, Title, Default Value
        Ret = InputBox("Please enter a #", "Determine Limit", 10000)
    
        If Ret = "" Then
            MsgBox ("You pressed the cancel button... or you pressed OK without entering anything")
        Else
            If IsNumeric(Ret) Then
                userInputValue = Val(Ret)
            Else
                MsgBox ("Incorrect Value")
            End If
        End If
    End Sub