How do you exit a VB form using a messagebox prompt?

Not sure quite what you're asking. If you mean. "I want to click a button, show a message box and unload my form depending on what the user's response is", then you would just use the MsgBox function to get a return value, then decide what to do from there.

Here's a snippet:

Private Sub cmdClose_Click()
Dim retCode As Integer
retCode = MsgBox("You clicked 'Close'...Are you sure you want to leave?", vbQuestion + vbYesNo, "Clicked A Button")
If retCode = vbNo Then
    Exit Sub
End If
Unload Me
End Sub

If on the other hand, you are asking how to control exiting a form gracefully, there's a couple of ways to do it, depending on how fancy you want to be. The most common way is to put some code in the "QueryUnload" event of your form. It also provides a way to find out HOW your form is closing (for instance, if you click the "X" on the upper right of the form, or if Windows is shutting down).

Here's a snippet:

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Dim retCode As Integer
If UnloadMode = vbFormControlMenu Then
    MsgBox "You can't close the form that way...Click the 'Close' Button.", vbCritical + vbOKOnly, "Closing Halted"
    Cancel = 1
    Exit Sub
End If
retCode = MsgBox("I'm trying to unload...Are you really sure you want to leave?", vbQuestion + vbYesNo, "Closing Form")
If retCode = vbNo Then
    Cancel = 1
    Exit Sub
End If
End Sub

There's even another way, using the Unload event of your form. It fires AFTER the QueryUnload event. It still gives you a way to cancel unloading, but doesn't let you know WHY the form is unloading.

Here's a snippet:

Private Sub Form_Unload(Cancel As Integer)
Dim retCode As Integer
retCode = MsgBox("Last chance...Are you really, REALLY sure you want to leave?", vbQuestion + vbYesNo, "Unloading Form")
If retCode = vbNo Then
    Cancel = 1
    Exit Sub
End If
End Sub

Anyway, this is probably way more information than you wanted. But, what the heck. Also, there's a really good section in the VB Help file entitled "Life Cycle of Visual Basic Forms". It's good reading, and will explain a lot of other stuff too. I highly recommend it.

Hope this helps. Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.