tags:

views:

35

answers:

2

I have created an Inputbox to get the username entered but stuck with the cancel button

Private Sub Form_Load()
fsUserName = UCase(InputBox("Please Enter your name.", "User Name", _
"dc"))

If fsUserName = "" Then
MsgBox "No name Entered." & Chr(13) & Chr(13) & _
"You must enter a name.", vbExclamation, "ERROR"
Form_Load
ElseIf VarType(fsUserName) = 0 Then 'If cancel clicked
cmdQuit_Click

End If

Also is there a way that when the X button on the form is clicked it executes cmdQuit_Click so that if the userclicks the command button Quit or X ,the Quit script is run.In the quit script there are message boxes and cleanup.

+4  A: 

You can use StrPtr() to detect if cancel was clicked;

Dim fsUserName As String

fsUserName = InputBox("Please Enter your name.", "User Name", "dc")

If (StrPtr(fsUserName) = 0&) Then
    MsgBox "Cancelled or X clicked"
ElseIf fsUserName = "" Then
    MsgBox "No name Entered." & vbCr & "You must enter a name.", vbExclamation, "ERROR"
Else
    fsUserName = UCase$(fsUserName)
    MsgBox fsUserName
End If

If you want to do something when the form unloads you can use the Form_Unload event or better the Form_QueryUnload event which fires before the actual unload & allows you to cancel it.
It will also tell you why the form is unloading (UnloadMode will be 0 if the red X is clicked)

Using "Unload Me" will raise both of the events.

Edit: Calling Form_Load in Form_Load like that will eventually fill up the stack, better to use a loop to look for a missing username.

Alex K.
Thanks Alex,the solution worked perfect for me.I would be glad if you could guide me the Loop part also.Thanks once again.
Dario Dias
A: 

Alex's answer using StrPtr, which I assume works as advertised, is good as far as it goes, but the better advice (IMO) is to avoid InputBox altogether. You can easily create your own using a dialog-style form, a textbox, and a couple of buttons, and maybe an icon if you like.

Rolling your own gives you complete flexibility and predictability, and once you have it you can use it in any future projects.

Jim Mack
VB6's InputBox() function is a very thin wrapper on the equivalent API call, which documents Cancel as returning a null pointer. In the rare case where an InputBox is useful that detection technique is fine - there is no reliability issue. However I agree InputBox() is a poor choice for production programs the average user will interact with.
Bob Riemersma
It was very nice of Jim to suggest that creating my own custom dialog box is far better than using inputbox.The dialog box can be given a much more professional look.Thanks
Dario Dias