# VBA First Macro

Open the VBE (+) and create a module (as described in VBA VBE Editor).

To understand how a VBA code works, copy the text bellow in the Code Window while the newly created module is selected in the Project Explorer ("Module1").

Sub HelloVBAWorld()

MsgBox "Hello VBA World"

End Sub


Your Code Window will be like this:

With this we have a macro called HelloVBAWorld which, when executed, sends the message "Hello VBA World" to the user.

## Running the Code - Msgbox

1. In the Code Window, click anywhere between the beginning of the subroutine (delimited as Sub) and the end of the procedure (delimited as End Sub)
2. Click Run Macro on the Toolbar(or press )

When running, the following text box should appear:

The MsgBox feature is widely used to leave warnings to users, whether running a routine, for example, or running a Workbook_Open event.

## About the Subroutine

The abbreviation Sub stands for Subroutine.

Sub indicates to VBA where the code starts while End Sub indicates where it ends.

Sometimes we will omit the Sub start and end declaration to highlight content:

Omiting the Sub declaration

    MsgBox "This is an example"


Showing the Sub declaration

Sub Example()

MsgBox "This is an example"

End Sub

The code should always be contained within a Sub and End Sub to run (unless it is contained between a Function and End Function for example, but we will see this later).

### Naming a Sub

All Sub needs to be followed by a name (in our example above, the name is "HelloVBAWorld").

The name must comply with the following rules:

• It must initiate with an alphabetical character
• It must not contain especial characters, such as: #, \$, %, &, !
• It must not contain whitespace characters, dots or commas
• It must not be a VBA reserved word like: And, Or, Sub

At the end of the name there must be parenthesis"()".

Type Sub, the name of the macro and press the Enter key, the VBA will automatically add the "()" and the End Sub.

## Consolidating Your Learning

Suggested Exercise

SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.