Reputation: 149
Just doing a quick exercise below, an input box that converts inches to cm's. I want to add to the error handler section so that after the msgbox appears explaining an error has occurred it loops back to the inputbox asking me to add inches to convert to centimeters. Thanks
Sub Exercise()
Dim m As Variant
Dim result
Dim ErrM As String
On Error GoTo ErrHandler
m = InputBox("How much in Inches would you like to convert to Centimeters?", "Inches to Centimeters", "Please Type here")
result = m * 2.54
MsgBox "There are " & result & " inches", , "Result"
Exit Sub
ErrHandler:
MsgBox ("An error occured, please type a number into the input box")
End Sub
Upvotes: 0
Views: 405
Reputation: 19641
There's no need for error handling in your specific case. Simply, throw the InputBox in a loop, check if the input is a number (e.g., using IsNumeric
), and decide whether you should continue or repeat based on that.
Example:
Do While True
m = InputBox("How much in Inches would you like to convert to Centimeters?", _
"Inches to Centimeters", "Please Type here")
If StrPtr(m) = 0 Then
' The user canceled the operation.
Exit Sub
ElseIf Not IsNumeric(m) Then
' The input is not a number.
MsgBox ("Please type a number into the input box.")
Else
' The input is a number. We continue with the code below.
Exit Do
End If
Loop
result = m * 2.54
MsgBox "There are " & result & " inches", , "Result"
Upvotes: 1
Reputation: 42236
Try this way, please:
Sub Exercise()
Dim m As Variant, result As Double
BackInp:
m = InputBox("How much in Inches would you like to convert to Centimeters?", "Inches to Centimeters", "Please Type here")
If Not IsNumeric(m) Then
MsgBox "An error occurred, please type a numeric value into the input box!", _
vbInformation, "Need to repeate the input..."
GoTo BackInp
End If
result = m * 2.54
MsgBox "There are " & result & " inches", , "Result"
End Sub
Upvotes: 0