Trouble with InputBoxes

Katana24 picture Katana24 · Apr 17, 2013 · Viewed 30.7k times · Source

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?

Answer

Alex K. picture Alex K. · Apr 17, 2013

Here is a way to catch most outcomes of interacting with the dialog;

Dim value As String
value = InputBox("Please enter a #", "Determine Limit", 10000)

If (StrPtr(value) = 0) Then
    MsgBox "You pressed cancel or [X]"

ElseIf (value = "") Then
    MsgBox "You did not enter anything"

ElseIf (Val(value) = 0 And value <> "0") Then
    MsgBox "Invalid number"

Else
    MsgBox "You entered " & value

End If