PDA

View Full Version : Error Handling for InputBoxes



moxieman19
12-03-2019, 08:39 AM
I'm trying to have some inputboxes for a byte-sized number, and when there's an error I want to display a msgbox saying "Please Enter a Number Between 1 and 10.". Here's what I have so far:


Sub Example()


Dim CodeLength As Byte, CodeRange As Byte


CodeLengthInput:
On Error GoTo CodeLengthError
CodeLength = InputBox("Enter Code Length")

CodeRangeInput:
On Error GoTo CodeRangeError
CodeRange = InputBox("Enter Code Range")

GoTo InputsOK

CodeLengthError:
MsgBox ("Please Enter a Number Between 1 and 10.")
GoTo CodeLengthInput
CodeRangeError:
MsgBox ("Please Enter a Number Between 1 and 10.")
GoTo CodeRangeInput

InputsOK:


End Sub





What happens when I run the above code is that the error handling performs correctly ONLY ONCE. On the second error, I get a run-time error window. This happens for both mismatch and overflow errors.

The confusing part is that if I put in an incorrect value for the first inputbox, get the error msgbox, put in a correct value, then put an incorrect value for the second inputbox, then I still don't get a second error msgbox - the error msgbox will only appear once no matter what.

Anybody have an idea on what I'm doing wrong? How do I get error handling to work correctly every time?

Paul_Hossler
12-03-2019, 01:17 PM
Instead of all those GoTo's, this might be simpler



Option Explicit


Sub Example()
Dim CodeLength As Byte, CodeRange As Byte
Dim bOK As Boolean


bOK = False
Do While Not bOK
CodeLength = InputBox("Enter Code Length, 0 to exit")
Select Case CodeLength
Case 0
Exit Sub
Case 1 To 10
bOK = True
Case Else
MsgBox ("Please Enter a Number Between 1 and 10.")
End Select
Loop


bOK = False
Do While Not bOK
CodeRange = InputBox("Enter Code Range, 0 to exit")
Select Case CodeRange
Case 0
Exit Sub
Case 1 To 10
bOK = True
Case Else
MsgBox ("Please Enter a Number Between 1 and 10.")
End Select
Loop
End Sub