Handling non integer in inputbox in VBA
excel, vba
Solution
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
Problem
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 ```