Creating a Macro Using VBA Editor

You can create a macro by writing the code in the VBA editor. In this chapter, you will learn where and how to write the code for a macro.

VBA Objects and Modules

Before you start coding for a Macro, understand the VBA Objects and Modules.

Objects

The VBA editor window opens.

Window Opens

You will observe the following in the Projects Explorer window −

Code

The code of your macro appears.

Code of Macro

Creating a Macro by Coding

Next, create a second macro in the same workbook – this time by writing VBA code.

You can do this in two steps −

Inserting a Command Button

Inserting Command Button1_Click

The Visual Basic editor appears.

Visual Basic

You will observe the following −

Coding the Macro

Your coding is half done by the VBA editor itself.

For example, type MsgBox “Best Wishes to You!” in the sub procedure Button1_Click (). A message box with the given string will be displayed when the command button is clicked.

Message Box

That’s it! Your macro code is ready to run. As you are aware, VBA code does not require compilation as it runs with an interpreter.

Running the Macro from VBA Editor

You can test your macro code from the VBA editor itself.

Macro From VBA

You can see that the button is selected. Click OK in the message box. You will be taken back to the VBA editor.

Running the Macro from Worksheet

You can run the macro that you coded any number of times from the worksheet.

Macro From Worksheet

You have created a macro by writing VBA code. As you can observe, VBA coding is simple.