Skip to main content
HomeTutorialsExcel

VBA Excel: How to Get Started and Make Your Work Easier

Learn how to effectively use VBA in Excel to automate tasks, create macros, and enhance your data processing skills with practical examples and best practices.
Sep 7, 2024  · 10 min read

Visual Basic for Applications (VBA) in Excel is a language that allows users to automate repetitive tasks and enhance Excel’s functionality far beyond its standard features. So, whether you're a beginner who wants to boost productivity or an advanced user seeking to streamline complex workflows, VBA is here to make things easier.

In this guide, I’ll explain foundational and advanced VBA concepts. However, if you're new to Excel, begin with Excel Fundamentals to build a solid foundation before advancing to VBA.

What is VBA in Excel?

Visual Basic for Applications (VBA) is a programming language used to automate tasks and enhance the functionality of Microsoft Office applications. You can use it with Excel, Word, Access, and other Office programs, althought it’s probably most widely used for creating custom macros in Excel, which we will look into.

Personally, the first time I used VBA was to automate a weekly report that used to take hours to compile manually. With just a few lines of code, I reduced the process to a single button click and saved a lot of hours. From then on, I know that investing some time in mastering it would pay off enormously in terms of productivity.

Advance Your Career with Excel

Gain the skills to maximize Excel—no experience required.

Start Today for Free

Important VBA Excel Terms

Before working with VBA, you must understand its key terms and concepts. So, here’s a list of some of the most used terms you'll encounter as you start automating tasks and building custom solutions in Excel.

  • Modules are the containers for VBA code, where procedures and functions are stored.

  • Objects are the building blocks of VBA. They represent elements like workbooks, worksheets, and cells.

  • Procedures are the blocks of code that perform specific tasks, often categorized as sub-procedures or functions.

  • Statements are the instructions within a procedure that tell Excel (or Word or Access) what actions to perform.

  • Variables store data that can be used and manipulated within your code.

  • Logical operators compare values and make decisions based on the results. They include operators like And, Or, and Not.

Getting Started with VBA in Excel

To begin using VBA, you'll need to access the VBA editor. This is where you'll write and edit your VBA code. Let's walk through how to get there:

Enabling the Developer tab 

The first step is to enable the Developer tab, which is often hidden on the Ribbon. To do so:

  • Right-click anywhere on the Ribbon

Ribbon in Excel

Ribbon in Excel. Image by Author.

  • Select the Customize the Ribbon... option. 

customizing the ribbon in Excel

Customize the Ribbon to enable the Developer tab. Image by Author.

  • A dialog box will appear. Check mark the Developer option and hit OK.

Selecting the Developer Option from a dialog box and hit OK in Excel

Selecting the Developer option. Image by Author.

You can now see a Developer tab at the top of the Ribbon.

Developer tab in Excel

The Developer tab is enabled on the Ribbon. Image by Author.

Opening the VBA editor 

Once the Developer tab is enabled, you can access the VBA editor. To do so, click the Developer tab and select Visual Basic from the options. You can also use the keyboard shortcut ALT + F11 to open the VBA editor directly.

Interface of VBA editor in Excel

VBA editor. Image by Author.

The VBA editor might initially seem intimidating, but it’s easy to use. Let’s understand its few key areas:

  • Code Pane is where you write and edit your VBA code.
  • Project Explorer shows a hierarchical view of the projects and modules in your workbook.
  • Properties Window displays properties for selected objects to customize their settings.

Interface of VBA in Excel

VBA interface in Excel. Image by Author.

Writing VBA Code in Excel

Now that you're familiar with the VBA editor, it's time to start writing some code. VBA code consists of different parts, like sub procedures and functions. These are sets of instructions that tell Excel what to do. Don't worry if you've never programmed before - I'll take it step by step. 

Writing a VBA subroutine

Before writing a macro, you have to create a macro environment. To do so, follow these steps:

  • Inside the VBA editor, select Insert > Module. A new module will be created with the default name, Module1. 

Insert a new module in VBA

Select Module under the Insert tab. Image by Author.

  • You can change the name of the module in the Properties pane.

Rename the newly created module in VBA in Excel

Rename the VBA module. Image by Author.

Now you know how to set up the environment for creating a macro, let's create our first macro together to display a message. By default, the code window opens when the module is created. If it doesn't work in your case, right-click on the module you created and click View Code. The code window will appear where you can write your macros.

Here, I’m creating a macro to display the message Hello, World!. To do so, I write the following code in the code pane:

Sub ShowMessage()
    MsgBox "Hello, World!"
End Sub 

Here:

  • Sub is the keyword for a subroutine, which is a block of code that performs a specific task. In VBA, a subroutine doesn't return a value.

  • ShowMessage is the name of the subroutine. You can name it whatever you like, as long as it follows VBA naming conventions (e.g., no spaces, can't start with a number).

  • () are used here to define the subroutine's parameters. Since no parameters are needed for this task, the parentheses are empty.

  • MsgBox is a built-in VBA function that displays a message box on the screen. 

  • End Sub statement indicates the end of the subroutine. Everything between Sub and End Sub is the code that will run when the subroutine is called.

  • Text strings in VBA are enclosed in double quotes. Here, we want the string Hello, World! to appear inside the message box.

Writing a VBA macro in a code pane in Excel

Writing a macro. Image by Author.

  • Now, it's time to run the code. Use the shortcut key F5. If you want to do it manually, go to the Developer tab and select Macros. Hit Run. 

Select the Macros option under the developer tab and run the Macro in Excel

Select the Macros option under the Developer tab. Image by author.

You can now see the message box appear on your Excel sheet.

message box in Excel

Message box. Image by Author.

Understanding objects in VBA 

In VBA, objects allow you to control different elements within Excel and automate tasks for more efficient workflows. There are three key objects: Workbook, Worksheet, and Range. Let’s understand each with a practical example.

The Workbook object is any Excel file that’s currently open. It allows us to perform actions such as adding new sheets or saving the existing sheets within the workbook. In this example, I want to add a sheet to the currently opened sheet and then save it. At first, I had Sheet1. To add another sheet, I write the following code:

Sub AddSheetAndSaveWorkbook()
    ' Adds a new worksheet to the active workbook
   ActiveWorkbook.Sheets.Add
    
    ' Saves the workbook
    ActiveWorkbook.Save
End Sub

This code works exactly the same as the previous code, but I’ve added comments here. Comments start with ' and they don't affect your code. We only add them for our convenience to make the code clearer. 

You can see another sheet, Sheet2 is created now.

Add and save a new sheet in the existing sheet using VBA in Excel

Add and save a new sheet in the existing sheet using VBA. Image by Author.

The Worksheet object represents the currently active sheet in Excel. With this, you can modify or manipulate the active sheet. For example, I want to change the name of the active sheet. To do so, I enter the following code:

Sub RenameActiveSheet()
    ' Renames the active sheet to "Sales Report".
    ActiveSheet.Name = "Sales Report"
End Sub

Code for changing the name of the worksheet using VBA in Excel

Changing the name of the worksheet using VBA. Image by Author.

Now, Sheet1 has been renamed to Sales Report.

Renamed the worksheet using VBA in Excel

Renaming the Excel worksheet using VBA. Image by Author.

The Range object refers to a specific group of cells or a single cell that we can handle as needed.  In the following example, I select a range of cells from F3 to I3 and change the background color. To do so, I write the following code:

Sub FormatRange()
    ' Selects the range from A1 to C6
    Range("F3:I3"). Select
    
    ' Changes the background color of the selected range to Green
    Selection.Interior.Color = RGB(101, 255, 143)
End Sub

Code for changing the color of the selected range using VBA in Excel

Selecting range and changing the color using VBA. Image by Author.

You can see the difference in results. 

Results of changing the color of the selected range using VBA in Excel

Changing the color using VBA in Excel. Image by Author.

Creating variables in VBA

Like other programming languages, VBA variables store two main data types, numbers and text. To use them in VBA, you must first declare the variable using the keyword according to your preferences, followed by the variable name and data type.

Keyword variableName As DataType

Here: 

  • Keyword can be Dim, Static, Public, and Private.

  • variableName refers to the name chosen for this variable (no spaces).

  • As is used to declare the variable type.

  • DataType refers to the variable type, such as Integer.

When working with variables, you also have to abide by some rules:

  • The length must be less than 255 characters.
  • No spaces are allowed between characters.
  • The name cannot start with a number.
  • Don’t use periods in the name.

Numeric data type

Numerical data types in VBA are used to store numeric values.

Data type Stored Range of values
Byte 1 Byte Stores integers from 0 to 255
Integer 2 Byte Stores whole numbers within the range of -32,768 to 32,767
Long 4 Bytes Stores larger whole numbers, ranging from -2,147,483,648 to 2,147,483,647
Single 4 Bytes Stores decimal numbers with single-precision
Double 8 Bytes Stores decimal numbers with double-precision
Currency 8 Bytes Stores numbers with fixed decimal places
Variant (text) Text’s length + 22 bytes 0 to 2 billion characters

Non-numeric data type

Non-numerical data types in VBA store values that aren't numbers.

Data type Stored Range of values
String String length Stores text
Date 8 Bytes Stores Date and time
Boolean 2 Bytes Stores True or False
Variant 16 Bytes Stores any data type and is used when the type is not known in advance

Automating Tasks with VBA Excel Macros

Macros are essentially a series of instructions created in VBA to perform repetitive tasks. Using a macro, you can record a series of actions, like formatting cells, copying data, or performing calculations. After saving the macro, we can re-apply these actions with a single click. This saves time, especially when working with large datasets or tasks.

For example, if you often format your reports the same way, you can record a macro that applies all the necessary formatting steps instead of doing it manually each time. Later, you can run this macro to format new data. We showed a couple of basic examples, but imagine doing more small actions with just one click. Even if you don’t have coding experience, you can still automate routine tasks to streamline workflow and reduce the chances of errors that can occur when performing repetitive actions manually.

Recording an Excel macro 

Let’s see how you can record a macro to make some formatting changes:

  • Go to the Developer tab > Record Macro button. 
  • A dialog box will appear. Give your macro a name like I did FormatCells.
  • Assign a keyboard shortcut if desired. I assigned it Ctrl+S.
  • Click OK to start recording.

Now that the macro starts recording, perform the actions you want to automate. For this example, I am recording some formatting changes to a simple table. Once you’ve completed it, go back to the Developer tab and click the Stop Recording button. Below, you can see the macro in action.

Recording a macro using VBA in Excel. Gif by Author.

Now, if you have another dataset in another sheet and want the same formatting in that dataset, too, instead of formatting the whole thing again, press the shortcut key you created (in my case, it’s Ctrl+S). Otherwise, go to sheet2 > Developer tab > Macros > Run to do it manually.

Using the Excel macro. Gif by Author.

Editing Excel macros 

After recording a macro, you can even tweak or customize its actions. Here’s how: 

  • Go to the Developer tab and click on Visual Basics
  • VBA editor will appear. Now, in the Project Explorer, search for the workbook where your macro is stored. 
  • Expand the Modules folder, then double-click the module that contains your macro. The code window will display the VBA code of your recorded macro.

Illustration of code performed when recording a macro in Excel

Code of recorded macro in Excel. Image by Author.

Each line of code shows the action you performed during the recording. From here, you can modify the recorded code to customize the macro per your choice. In my case, I set the Selection.Font.Bold to False to remove the bold formatting. Once the edits are done, save the changes by clicking the save button or press Ctrl+S and Run the code to apply changes. Customizing the macro in VBA in Excel

Customizing the Excel VBA macro. Image by Author.

After running your macro, you can see the results — the previously bold columns are no longer bold. 

Results of the macro edited manually in VBA Excel

Using a macro in Excel. Image by Author

Writing custom Excel macros 

There may be some advanced tasks where you can’t record a macro. In such cases, you have to write a macro from scratch. For example, I want to copy the data from one worksheet to another. Here’s how I write a custom macro:

  • Open the VBA editor manually in the first sheet or press Alt+F11.
  • Insert a new module.
  • Write the following code in the code pane.
Sub CopyData()
Sheets("Sheet1").Range("B1:E21").Copy Destination:=Sheets("Sheet2").Range("B1")
End Sub
  • Save the macro and hit Run.

Now, you can see that the data from Sheet1 has been copied to Sheet2.

Step by step guide on writing a custom macro in VBA in Excel

Writing a custom macro using VBA. Gif by Author.

Final Thoughts 

From automating repetitive tasks to creating complex macros, VBA opens up a world of possibilities within Excel. As you become more comfortable with the basics, practice writing code and gradually explore the more advanced features of VBA. Remember, the key to mastering VBA—or any programming language—is consistent practice and a willingness to experiment. To further enhance your skills, consider exploring these additional resources. The Data Analysis in Excel and Learn Excel courses are excellent for learning more about Excel's features. 

If you want to expand your coding knowledge beyond VBA, the How to Become a Programmer in 2024 guide offers a roadmap. Do check it out if you are interested in the field. Additionally, the Financial Modeling in Excel course is perfect for those interested in creating detailed financial models.

Learn Excel Fundamentals

Gain skills to use Excel effectively—no experience required.

Photo of Laiba Siddiqui
Author
Laiba Siddiqui
LinkedIn
Twitter

I'm a content strategist who loves simplifying complex topics. I’ve helped companies like Splunk, Hackernoon, and Tiiny Host create engaging and informative content for their audiences.

Frequently Asked VBA Excel Questions

What is the purpose of the Explicit statement in VBA?

Explicit helps ensure that all variables are explicitly declared before use, reducing bugs and making your code more maintainable.

How do I password-protect my VBA code?

You can protect your VBA code by going to the VBA editor > Tools > VBAProject Properties > Protection tab. Check the Lock project for viewing option and set a password.

What is the difference between ActiveWorkbook and ThisWorkbook in VBA?

ActiveWorkbook refers to the workbook currently in focus, which may not contain the VBA code. Thisworkbook refers to the workbook where the VBA code resides, regardless of which workbook is active.

What are UserForms in VBA, and how can they be used?

UserForms are custom dialog boxes in VBA that allow users to input data. They can be used to create interactive forms for data entry, selection, or user interaction requiring a custom interface.

Topics

Learn Excel and VBA with DataCamp

Course

Financial Modeling in Excel

3 hr
7.7K
Learn about Excel financial modeling, including cash flow, scenario analysis, time value, and capital budgeting.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

cheat-sheet

Excel Formulas Cheat Sheet

Learn the basics of Excel with our quick and easy cheat sheet. Have the basics of formulas, operators, math functions and more at your fingertips.
Richie Cotton's photo

Richie Cotton

18 min

tutorial

How to Clean Data in Excel: A Beginner's Guide

Learn essential data cleaning techniques in Excel, including removing duplicates, handling missing values, and maintaining consistent formatting.
Laiba Siddiqui's photo

Laiba Siddiqui

15 min

tutorial

Conditional Formatting in Excel: A Beginner’s Guide

Explore conditional formatting in Excel with simple to advanced examples and their best practices.
Joleen Bothma's photo

Joleen Bothma

7 min

tutorial

Data Types in Excel and Their Uses: A Complete Guide

Learn to identify and format all types of data in Excel, then explore valuable tips on converting between data types to make your spreadsheet more functional.
Laiba Siddiqui's photo

Laiba Siddiqui

9 min

tutorial

Python Excel Tutorial: The Definitive Guide

Learn how to read and import Excel files in Python, write data to these spreadsheets, and find the best packages to do this.
Natassha Selvaraj's photo

Natassha Selvaraj

30 min

tutorial

How to Create a Dashboard in Excel in 3 Easy Steps

Learn everything you need to know about how to create a dashboard in Excel, with tips and examples.
Joleen Bothma's photo

Joleen Bothma

12 min

See MoreSee More