What is an Excel Macro?
If you’re an Excel user, you’ve probably faced the need to perform repetitive tasks. Well, macros allow you to automate those repetitive tasks, saving you time and effort when working in Excel. If you want to learn how to use them, you’ve come to the right place!
Macros in Excel are written in a programming language called Visual Basic for Applications, commonly known as VBA. The good news is that you don’t have to be a programming expert to get started in this world.
In this first tutorial, we will teach you how to create your first Excel macro. The goal is to display a message that says “Hello World!”. Just follow these steps:
Activate the Developer Tab in Excel
First, make sure the “DEVELOPER” tab is active in the ribbon, as it provides options of interest for programmers.
To do this, open a new Excel file and check if this tab is available.
If it’s not, right-click anywhere on the ribbon and select “Customize the Ribbon…”. Then, check the “Developer” box and click “OK”.
Access the VBA Editor
You can access the VBA editor in two ways: a) By pressing the Alt + F11 key combination
b) By clicking the “View Code” button in the “DEVELOPER” ribbon.
Add a New Module in VBA
Within the VBA environment, right-click on the project folder of your Excel workbook (usually located on the left side of the screen). From the dropdown menu, select Insert > Module.
Write the VBA Program
We will write a program that displays the message “Hello World!”. To do this, we will create a subroutine (Sub) named “MyFirstMacro”. The name of the subroutine should not contain spaces or special characters. The subroutine starts with the word “Sub” and ends with “End Sub”.
Inside the subroutine, we will define a variable of type “string” (we’ll talk more about variable types later) to store the text to be displayed. We will name this variable “strGreeting”. The code should look as follows:
Sub MyFirstMacro() Dim strGreeting As String strGreeting = "Hello World!" MsgBox strGreeting End Sub
Run the Program in VBA
You can run the program in various ways: a) By pressing the F5 key
b) By clicking the Run Macro button
c) By assigning the macro to a button. To do this, go to the “DEVELOPER” tab and select “Insert/Button”. Then click anywhere on the sheet to place the button. Excel will ask for the name of the macro associated with that button; select “MyFirstMacro” and click OK.
Once you run the macro, the following message should appear:
Congratulations! You’ve written your first macro.
Save the Excel Workbook with Macros Enabled
Make sure to save documents containing macros with the extension “.xlsm” (macro-enabled).
Want to know more? Contact us…