Understanding MsgBox in Visual Basic

The MsgBox function in Visual Basic and VB6 is used to display a message dialog box to the user. It can show text, icons, and buttons, and can return a value indicating which button the user clicked.

In VB.NET, MsgBox still exists for compatibility, but the recommended function is MessageBox.Show from the .NET Framework.

Basic VB6 Example


Private Sub Command1_Click()
    MsgBox "Hello, World"
End Sub
    

This displays a simple message box with an OK button.

VB6 Example With Buttons


Dim response As Integer
response = MsgBox("Do you want to continue?", vbYesNo + vbQuestion)

If response = vbYes Then
    MsgBox "Continuing..."
Else
    MsgBox "Cancelled."
End If
    

VB.NET Equivalent

In VB.NET, you can still use MsgBox, but MessageBox.Show is preferred:


MessageBox.Show("Hello, World")
    

Common MsgBox Button Options

Constant Description
vbOKOnly Displays an OK button
vbOKCancel OK and Cancel buttons
vbYesNo Yes and No buttons
vbYesNoCancel Yes, No, and Cancel buttons
vbRetryCancel Retry and Cancel buttons

Common MsgBox Icon Options

Constant Icon
vbInformation Information icon
vbExclamation Warning icon
vbCritical Error icon
vbQuestion Question mark icon

Return Values

MsgBox returns an integer representing the user's choice:

Constant Value User Clicked
vbOK 1 OK
vbCancel 2 Cancel
vbYes 6 Yes
vbNo 7 No

When to Use MsgBox


PeatSoft - VB.NET - Educational Reference - AI