Messages, Pop-ups, and Alerts – MsgBox()

Displaying Messages and Alerts in Excel Visual Basic

The MsgBox() function can be used to display alerts or prompts and even get some feedback from users.

The general format is:

MsgBox(MessageString, Buttons, Title, HelpFile, Context)

Buttons, Title, HelpFile, and Context are all optional, leaving your basic required function call:

MsgBox(MessageString)

OR

MsgBox MessageString

The optional Buttons parameter uses a Numerical Constant. You can either use the Constant variable name or the value it represents. The purpose of the Buttons is to display a button to the user in order to receive feedback.

Constant

Value
vbOKOnly 0
vbOKCancel 1
vbAbortRetryIgnore 2
vbYesNoCancel 3
vbYesNo 4
vbRetryCancel 5
vbCritical 16
vbQuestion 32
vbExclamation 48
vbInformation 64
vbDefaultButton1 0
vbDefaultButton2 256
vbDefaultButton3 512
vbDefaultButton4 768
vbApplicationModal 0
vbSystemModal 4096
vbMsgBoxHelpButton 16384
VbMsgBoxSetForeground 65536
vbMsgBoxRight 524288
vbMsgBoxRtlReading 1048576

When you create a message box using the various buttons, you get a possible return value:

Constant Value
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7

 

Example 1: A Simple Message Box

Private Sub CommandButton1_Click()
     MsgBox "Hello"
 End Sub

example1

Example 2: Message Box with a Return Value

Private Sub CommandButton1_Click()
     Dim MsgBoxReturnValue As Integer
    
     MsgBoxReturnValue = MsgBox("Do you like pancakes?", vbYesNo + vbCritical, "Important Question")
    
     If (MsgBoxReturnValue = vbYes) Then
         MsgBox "YES!", vbInformation, "You Answered:"
     Else
         MsgBox "NO!", vbInformation, "You Answered:"
     End If
 End Sub

The above code will first create this message box:

pancakeQuestion

Answering “Yes” will produce this response:

yesPancakes

Answering “No” will produce this response:

noPancakes.png

 

Excel VBA Resources

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: