PDA

View Full Version : InputBox Retry Loop



ldoodle
01-09-2015, 08:32 AM
Hey,

This applies to any VBA application, not just Outlook.

I've got this at the moment, which basically checks the value of an input box and offers a Retry or Cancel box if user input it not accepted.

The problem I'm having, is that the first time r is set to vbRetry it persists so even if the user enters valid data in the input box after pressing retry, as r still = vbRetry it gets stuck in a permanent loop, until Cancel on the input box (not the msg box) is pressed.


Do

r = -1 <------ this fixes it, but is it right?

InputIRN = InputBox(Title:="New " & EntityDesc(Entity) & " Email", Prompt:="Enter IRN(s):" & vbNewLine & vbNewLine & "Note: Separate multiple IRNs with a semi-colon or a comma.", Default:=InputIRN)

If StrPtr(InputIRN) = 0 Then

r = vbCancel

Else

If ((InputIRN = "") Or (InputIRN = "False") Or (InputIRN = vbNullString)) Then

r = MsgBox("You did not enter an IRN.", vbRetryCancel + vbInformation, "Missing IRN")

ElseIf InStr(1, InputIRN, "#") Then

r = MsgBox("# characters cannot be used in IRNs.", vbRetryCancel + vbInformation, "Invalid characters")

End If

End If

If r = vbCancel Then Exit Sub


Loop While r = vbRetry

...
other code goes here
...




Basically, once all is good with the input box, the rest of the code (outside the Do loop) should be run. If cancel is pressed on the input box or the msg boxes then it should exit.

I can 'fix' it by putting r = -1 (or any other value that's not vbRetry or vbCancel) as the first thing in the Do loop, but is that the correct way?

Can what I have be improved?

Thanks

gmayor
01-11-2015, 01:23 AM
If you add a message box to display R before 'Loop While' you can see the problem. The value of R is never reset.

You can set it as you have done at the start of the loop or provide an additional option in the IF statement e.g. as follows (the code does not indicate what EntityDesc(Entity) relates to so the example omits it).



Sub Macro1()
Dim InputIRN As String
Dim R As Long
Do
'InputIRN = InputBox(Title:="New " & EntityDesc(Entity) & " Email", _
Prompt:="Enter IRN(s):" & vbNewLine & vbNewLine & _
"Note: Separate multiple IRNs with a semi-colon or a comma.", _
Default:=InputIRN)
InputIRN = InputBox(Title:="New Email", _
Prompt:="Enter IRN(s):" & vbNewLine & vbNewLine & _
"Note: Separate multiple IRNs with a semi-colon or a comma.", _
Default:=InputIRN)
If StrPtr(InputIRN) = 0 Then
R = vbCancel
Else
If ((InputIRN = "") Or (InputIRN = "False") Or (InputIRN = vbNullString)) Then
R = MsgBox("You did not enter an IRN.", vbRetryCancel + vbInformation, "Missing IRN")
ElseIf InStr(1, InputIRN, "#") Then
R = MsgBox("# characters cannot be used in IRNs.", vbRetryCancel + vbInformation, "Invalid characters")
Else
R = 1 'vbOK
End If
End If
MsgBox R
If R = vbCancel Then Exit Sub
Loop While R = vbRetry
MsgBox InputIRN
End Sub

ldoodle
01-12-2015, 04:28 AM
Thanks, I like that!