Basics of VBA: Message Box

  

Bottom Line:

Learn how to use different VBA Message Box options.

Note:

Sample Excel with code included below. Please make use of it.

Skill Level: Beginner

Sample File: VBA-MessageBox.xlsm

 

Syntax:


Prompt − Required parameter, a string, that is displayed as a message in the dialog box.

All the others are optional parameters. Please check the below image for more info (Credits: Microsoft)


Various MessageBox options:

    1. with only 'Ok' button:

                                    

    Code:

Private Sub OkMsgBox()
a = MsgBox("MsgBox with only 'Ok' button", 0, "Choose options")
If a = 1 Then
MsgBox ("'Ok' is selected")
End If
End Sub
view raw OkMsgBox.vbs hosted with ❤ by GitHub


2. with 'Ok' and 'Cancel' buttons:

                                   

    Code:

Private Sub OkCancelMsgBox()
a = MsgBox("MsgBox with 'Ok' & 'Cancel' buttons", 1, "Choose options")
If a = 1 Then
MsgBox ("'Ok' is selected")
ElseIf a = 2 Then
MsgBox ("'Cancel' is selected")
End If
End Sub
view raw OkCancel.vbs hosted with ❤ by GitHub

    


3. with 'Abort', 'Retry' and 'Ignore' buttons:

                                    

    Code:

Private Sub AbortRetryIgnore()
a = MsgBox("MsgBox with 'Abort', 'Retry' & 'Ignore' buttons", 2, "Choose options")
If a = 3 Then
MsgBox ("'Abort' is selected")
ElseIf a = 4 Then
MsgBox ("'Retry' is selected")
ElseIf a = 5 Then
MsgBox ("'Ignore' is selected")
End If
End Sub

    


4. with 'Yes', 'No' and 'Cancel' buttons:

                                    

    Code:

Private Sub YesNoCancel()
a = MsgBox("MsgBox with 'Yes', 'No' & 'Cancel' buttons", 3, "Choose options")
If a = 6 Then
MsgBox ("'Yes' is selected")
ElseIf a = 7 Then
MsgBox ("'No' is selected")
ElseIf a = 2 Then
MsgBox ("'Cancel' is selected")
End If
End Sub
view raw YesNoCancel.vbs hosted with ❤ by GitHub

    


5. with 'Yes' and 'No' buttons:

                                    

    Code:

Private Sub YesNo()
a = MsgBox("MsgBox with 'Yes' & 'No' buttons", 4, "Choose options")
If a = 6 Then
MsgBox ("'Yes' is selected")
ElseIf a = 7 Then
MsgBox ("'No' is selected")
End If
End Sub
view raw YesNo.vbs hosted with ❤ by GitHub

    

Comments

Popular posts from this blog

Sending Gmails using Excel VBA