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.
Before you start coding for a Macro, understand the VBA Objects and Modules.
The VBA editor window opens.
You will observe the following in the Projects Explorer window −
Your macro enabled workbook – MyFirstMacro.xlsm appears as a VBA Project.
All the worksheets and the workbook appear as Microsoft Excel Objects under the project.
Module1 appears under Modules. Your macro code is located here.
Click Module1.
Click the View tab on the Ribbon.
Select Code from the dropdown list.
The code of your macro appears.
Next, create a second macro in the same workbook – this time by writing VBA code.
You can do this in two steps −
Insert a command button.
Write the code stating the actions to take place when you click the command button.
Create a new worksheet.
Click in the new worksheet.
Click the DEVELOPER button on the Ribbon.
Click Insert in the Controls group.
Select the button icon from Form Controls.
The Visual Basic editor appears.
You will observe the following −
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.
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.
You can test your macro code from the VBA editor itself.
Click the Run tab on the Ribbon.
Select Run Sub/UserForm from the dropdown list. The message box with the string you typed appears in your worksheet.
You can see that the button is selected. Click OK in the message box. You will be taken back to the VBA editor.
You can run the macro that you coded any number of times from the worksheet.
You have created a macro by writing VBA code. As you can observe, VBA coding is simple.