Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling non integer in inputbox in VBA

Tags:

excel

vba

I have a variable called "need" that is defined as an integer. An input box come up and prompts the user. If they type an integer it displays Msgbox "Got your number". If I type a string I get Runtime error '13': type mismatch. I thought if I just used an Else statement, it would say try again. It is not doing that though. Do I need error handling in the Else statement? And if so, what would the line(s) be?

Sub gadgetmanuf()

Dim need As Integer
'Dim rawneed As Single
'Dim rawavailable As Single


    need = InputBox("How many gadgets are needed?", "Insert a number")

    If TypeName(need) = "Integer" Then
        MsgBox ("Got your number")
    Else
        MsgBox ("Try again")
    End If

End Sub
like image 466
user2859603 Avatar asked Nov 26 '25 14:11

user2859603


1 Answers

Using an Application.InputBox with type 1 forces the user to enter a number (provides its own error message for text, ranges etc). So all you need to handle is the Cancel option, ie

The code below uses a variant to handle this, as using Cancel with an Integer or Long gives 0 - which could be a valid entry.

Sub TaylorWalker()
redo:
vStr = Application.InputBox("How many gadgets are needed?", "Enter a number", , , , , , Type:=1)
If vStr = False Then GoTo redo
End Sub

longer option

Test that the entered variable is greater than 0

Sub EddieBetts()
Dim StrPrompt As String
Dim lngNum As Long

StrPrompt = "How many gadgets are needed?"
redo:
lngNum = Application.InputBox(StrPrompt, "Enter an integer number (numbers will be rounded)", , , , , , Type:=1)
If lngNum < 1 Then
    StrPrompt = "How many gadgets are needed - this must be a postive integer"
    GoTo redo
End If

MsgBox "User entered " & lngNum

End Sub
like image 57
brettdj Avatar answered Nov 28 '25 09:11

brettdj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!