I am trying to understand why the following code is not giving me the expected behaviour.
I would like to ask the user for a decimal number (double). I have an error handler below but the way this program behaves, it will still throw errors when I input either a word or number. It will catch the error when I don't put anything though (empty input).
When I remove the if condition, it will work as expected but I do not know how to catch empty user inputs.
Any ideas would be greatly appreciated!
Sub MainTask()
Dim userInput As Double
TryAgain:
On Error GoTo ErrorHandler
userInput = InputBox("What is the amount purchased you would like to search for? ($)")
If Len(userInput) = 0 Then
Exit Sub
End If
MsgBox "You have entered a valid value!"
Exit Sub
ErrorHandler:
MsgBox "Please enter a valid value."
GoTo TryAgain
End Sub
vbaGoTo TryAgainwithin the error handler you are still within the error handler for the current error so subsequent errors are unhandled. ReplacingGoTo TryAgainwithResumewould fix this but its not a very good way of doing things, for example the user will get an error on the cancel button, you should use a string and test it against""andIsNumeric()userInput = application.InputBox("What is the amount purchased you would like to search for? ($)", type:=1). For general case of handling inputs, refer to Scott Craner's answer.