VBA  II - Message Box

 

Yesterday I have shown that how we can display phrases in a range of cells and also perform arithmetic operations in MS Excel. Today, I shall demonstrate how we can display  message boxes in a MS Excel worksheet . A message box normally act as a dialog box where users can interact with the computer, it is able to perform certain actions in response to what the user clicks or selects. The format for a message box is as follows:

message=MsgBox(Prompt, Style Value,Title)

The first argument, Prompt, will display the message in the message box. The Style Value determines what type of command button will appear in the message box. . The Title argument will display the title of the message board. message is a variable that holds values that are returned by the MsgBox ( ) function. The values are determined by the type of buttons being clicked by the users. It has to be declared as Integer data type in the procedure or in the general declaration section. Please refer to lesson 10 for the detail listings of the Style Value as well as the returned value.

In this example, I create three command buttons which show different Options. I put in a bit of program codes in the last button which involve the use of If...Then...Elseif statements.

 

This is the message box displayed by clicking the first message box

The codes are as follows:

Private Sub CommandButton1_Click()
MsgBox ("Welcome to VBA Programming")
End Sub

This is the message box displayed by clicking the first message box

The codes are as follows:

 

Private Sub CommandButton3_Click()
Dim message As Integer
message = MsgBox("Click Yes to Proceed, No to stop", vbYesNo, "Login")
If message = 6 Then
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
ElseIf message = 7 Then
ActiveWorkbook.Close
End If
End Sub

 

 

 

 

 

 

 

  [Previous Lesson] [Back to VBA Tutorial] [Next Lesson]