Caught in Loop - Cancel Button Not Responding

crhodus

Registered User.
Local time
Today, 15:54
Joined
Mar 16, 2001
Messages
257
I have problem with my code. It prompts the user to enter in their name. If they select OK without entering in their name, they are given a different message and asked continuiously until they supply a name.

My problem is that the cancel button on the input box does not work. It continues to ask for a name. Here is the code as I have it in my functon

Public Function Input_User_Name()
Input_User_Name = InputBox("Please enter your name.")

If Input_User_Name = "" Then
Do Until Input_User_Name <> ""
Input_User_Name = InputBox("You MUST enter your name before continuing. Please enter your name.")
Loop
End If

strInput_User_Name = Input_User_Name

End Function


Thanks!
 
The flaw in your logic is that you must specifically test for the cancel condition and exit the loop when it is found. This is a bit more of a trap for young players than one would expect because Access returns, in this situation a null string ("") both when OK is clicked with no name entered, AND when cancel is clicked. Tricky. This means that, when you do test for cancel you can't tell what what the user has done. Gob Bless Microsoft!! You must therefore ask if cancel is intended, and exit the loop if it is. the following code will work:

Public Function RunIt()
Dim strInput_User_Name As String

strInput_User_Name = Input_User_Name()

MsgBox "My Name Is: " & strInput_User_Name

End Function

Public Function Input_User_Name()
Dim MsgResult
Input_User_Name = InputBox("Please enter your name.")

If Input_User_Name = "" Then
Do Until Input_User_Name <> ""
Input_User_Name = InputBox("You MUST enter your name before continuing. Please enter your name.")
If Input_User_Name = "" Then
MsgResult = MsgBox("Cancel?", vbYesNo + vbQuestion)
If MsgResult = vbYes Then Exit Do
End If
Loop
End If

'strInput_User_Name = Input_User_Name 'This should be done outside of the function since Input_User_Name itself caries the value - this line is redudant here

End Function

As a good programming practice, always indent your logic. It will help you, when you return those many months later (or someone strange to your code does) intrepret the logic more easily.

Cheers. I hope this is of help. And don't worry, we ALL get lost in our own code from time to time, even if it is only a few lines!! ;-))
 
I retract my remark about indenting your code. Mine was beautifully indented and the HTML of this web page seems to have undone it all. :-( No doubt it did the same to you.

Sorry! :-)

[This message has been edited by David Fletcher (edited 05-11-2001).]
 
Thanks for your help. It works great. I'm having to teach myself VBA. About the only references I have are this forum and the help files.
 

Users who are viewing this thread

Back
Top Bottom