Execute vba in excel

Do you want to learn how to run a VBA macro in Microsoft Excel? This guide will show you all the methods you can use to run your VBA code.

Microsoft Excel is a powerful spreadsheet application that offers users a variety of features and capabilities. One of the most popular features of Excel is the ability to create and run VBA macros.

A macro is a small scripts written in the VBA (Visual Basic for Applications) programming language that can be run in your desktop Excel app.

Macros can save you a lot of time and energy when working in Excel. They can be used to automate tedious tasks and save you hours of work each week.

But in order to leverage this time saving tool, you will need to know how to run your VBA macros.

Follow this guide and you’ll be able to start running macros like a pro in no time!

Run VBA Macro from the Developer Tab

The most common method for running a macro is from the Developer tab in the Excel ribbon.

This tab is hidden by default, so you will need to enable the Developer tab in your desktop Excel app first.

Follow these steps to run a VBA macro from the Developer tab.

  1. Go to the Developer tab.
  2. Press the Macros command in the Code section.

This will open the Macro menu which lists all the macros available to run.

  1. Select the macro which you want to run.
  2. Press the Run button.

That’s it! Your chosen macro code will now execute!

💡 Tip: Use the Macros in dropdown option to select the location of macros to run. You can select a specific workbook, All Open Workbooks, or This Workbook.

Run VBA from the View Tab

The Macro command is also available in the View tab.

Go to the View tab and press the Macros button to launch the Macros menu.

This opens the same Macro dialog box as before and you can select the macro and press the Run button.

Run VBA Macro from Macro Menu with a Keyboard Shortcut

There is an easier way to open the Macro menu! There’s no need to use the Developer or View tab since there is a dedicated keyboard shortcut to open the Macro menu.

You can use the Alt + F8 keyboard shortcut to open the Macro menu.

Run VBA Macro from a Keyboard Shortcut

You can entirely bypass the Macro dialog box by assigning a keyboard shortcut to your desired Macro.

If this is a macro that you want to use a lot, then assigning a shortcut is a good way to avoid the many clicks needed when running a macro through the Macro menu.

Follow these steps to assign your macro a dedicated keyboard shortcut.

  1. Open the Macro menu.
  2. Select the macro to which you want to assign a keyboard shortcut.
  3. Press the Options button.

This will open up the Macro Options menu where you can add a description for the macro and assign a keyboard shortcut.

  1. Add a character into the Shortcut key input box.
  2. Press the OK button in the Macro Options menu.
  3. Press the Cancel button in the Macros menu.

⚠️ Warning: This chosen shortcut key will override any existing keyboard shortcut, so you should avoid using keys taken by commonly used shortcuts such as copy, paste etc.

A lot of Ctrl and single key combinations are already taken with commonly used commands, so you might want to create a Ctrl + Shift shortcut instead.

💡 Tip: Hold the Shift key while entering a key in the Shortcut key input to create a Ctrl + Shift shortcut.

Run VBA Macro from a Form Control Button

If other people are using your spreadsheet solution, they might not realise they can run your macros to help complete their work.

This is where a button is the preferred choice to run a macro. It makes the act of running your macro easy and obvious!

You can create a Form Control Button to run the macro when you click the button. This can be placed anywhere in the spreadsheet since is floats over top of the grid. This means it won’t interfere with the rest of your data or formulas.

Follow these steps to insert a Form Control Button and assign a macro to it.

  1. Go to the Developer tab.
  2. Click on the Insert command.
  3. Choose the Button option found in the Form Controls section.

This will not actually insert a button yet. You will notice your cursor has now turned into a small black plus sign. This will allow you to draw a button in your sheet.

  1. Left click and drag anywhere in the sheet.

When you release the click and drag action, the Assign Macro menu will immediately pop up and you will be able to assign your macro to the button.

  1. Select your macro.
  2. Press the OK button.

Now you have a button in your sheet which will run your select VBA macro when clicked.

💡 Tip: Righ click on the button and select Edit Text to change the text displayed on the button.

Run VBA Macro from any Shape, Icon, or Image

Form Control buttons are pretty ugly and outdated. They also don’t have many options to customize the look, but thankfully they aren’t the only way to make a button to run your macros!

There are some much more stylish options like using an image, shape, or icon as a button to run your macros.

Follow these steps to assign a macro to any object such as an image, shape, or icon.

  1. Right click on the object.
  2. Select Assign Macro option from the menu.
  3. Select the macro from the Assign Macro menu.
  4. Press the OK button.

Now when you click on the shape, image, or icon it will execute the macro code!

Run VBA Macro from a Quick Access Toolbar Command

Another option is to add your most frequently used macros to the Quick Access Toolbar.

The Quick Access Toolbar is a customizable set of commands that are always visible so you can easily use them at any time. You can even add a macro so it can be run with a click.

Follow these steps to add a macro to your Quick Access Toolbar.

  1. Right-click anywhere on the Quick Access Toolbar.
  2. Select the Customize Quick Access Toolbar option from the menu.

This will open the Excel Options menu on the Quick Access Toolbar section.

  1. Select Macros from the Choose commands from dropdown.
  2. Select the macro you want to add to your Quick Access Toolbar.
  3. Press the Add button.
  4. Press the OK button.

When you press the Add button you will see the selected macro gets added to your list of commands. You can use the Up and Down arrow buttons to adjust the order this macro will appear in your commands.

💡 Tip: Press the Modify button in the Excel Options to change the icon and label of the macro that will appear in your Quick Access Toolbar!

Now you should have a new icon available in the Quick Access Toolbar. Click on this to run your select macro.

💡 Tip: An easy way to use the commands in your Quick Access Toolbar is with the Alt hotkey shortcuts. In this example, the command is in the 8th position starting from the undo command, so you can press the Alt + 8 to run the macro.

Run VBA Macro from a Custom Ribbon Command

If you have an entire repertoire of macros and you’re running out of room in the Quick Access Toolbar, then adding a custom ribbon tab to organize your macros could be the ideal solution.

Excel allows you to add your own custom ribbons and fill them with your favorite macros as well as any other commands you frequently use.

Follow these steps to add a macro to the Excel ribbon.

  1. Right click anywhere on the Excel ribbon.
  2. Select the Customize the Ribbon option from the menu.

This will open the Excel Options menu on the Customize Ribbon section.

  1. Press the New Tab button to create your new ribbon tab.

  1. Press the Rename button to give your tab a name.

Each tab will need at least one group, and this is automatically created when you create a new tab. You can also rename the group. Both of these names will be displayed in your Excel ribbon.

Now you will be able to add a macro into the new tab and group.

  1. Select the Macros option from the Choose commands from dripdown.
  2. Select the macro which you want to add into the ribbon.
  3. Press the Add button.
  4. Press the OK button.

💡 Tip: Select the tab and use the Up or Down arrow buttons to adjust the position of the new tab in your ribbon.

You now have a new custom tab that can hold all your most frequently used macros. 😃

Run VBA Macro from Visual Basic Editor Run Menu

The visual basic editor (VBE) is the environment where you write VBA code, so it makes sense that you should be able to also run your code from it.

A lot of people like to test their code as they develop their solutions and this means frequently running your macros from the the editor. Your current code can always be run from the Run menu in the VBE.

Follow these steps to run your macro from the Run menu in the visual basic editor.

  1. Select the macro you want to run.

You can select the macro by either placing the cursor in the code or selecting the macro name from the dropdown menu in the top right.

  1. Go to the Run menu.
  2. Select the Run Sub/UserForm option from the menu.

This will run your selected macro!

Run VBA Macro from Visual Basic Editor Toolbar

The visual basic editor comes with a toolbar for easy access to the most frequently used commands.

Follow these steps to run your macro from the toolbar.

  1. Select the macro you want to run.
  2. Press the Play button in the toolbar.

This will run your selected macro!

📝 Note: If you don’t see this toolbar you might need to enable it. Go to the View menu then Toolbars and check the Standard option.

Run VBA Macro from Visual Basic Editor Keyboard Shortcut

There are a lot of very useful keyboard shortcuts for using the visual basic editor.

Running a macro from the VBE is a very common task, so it’s no surprise there is also a keyboard shortcut available for this.

Press the F5 key while in the VBE and the currently selected macro will run!

Run VBA Macro from Another Macro

You can easily run a macro from a macro in Excel.

This is a good practice when it comes to programming. Creating smaller procedures and then reusing them within your main macro can be more efficient to run and easier to maintain the code.

Sub ExampleCode()
    MsgBox ("Hello world!")
End Sub

Sub MainCode()
    Call ExampleCode
    MsgBox ("Goodbye!")
End Sub

You can easily run any macro from within a macro using a single line of code. The above example will run the ExampleCode macro from the MainCode macro.

Run VBA Macro from a Worksheet Event

Did you know you can automatically run a macro?

You can automatically run a macro based on events that happen in your Excel worksheet!

For example, you can have a macro run anytime someone changes a value in the sheet.

Follow these steps to create a worksheet event-driven macro.

  1. Select the Sheet in which you want to trigger the macro. All your workbook sheets will be listed in the Microsoft Excel Object folder of the VBE Projects.
  2. Select the Worksheet options from the dropdown menu.
  3. Select the event type that should trigger your macro.
Private Sub Worksheet_Change(ByVal Target As Range)

End Sub

When you select the type of event, it will insert a bit of code into the editor. For example, the Change event trigger will insert the above code.

  1. Place any code you want to run when the event occurs inside the generated code.

If you have an existing macro that you want to run, you can call it using a Call YourMacroName single line of code.

This macro will now run anytime you make changes in any cell within Sheet1.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then Call ExampleCode
End Sub

You might want to limit the macro to only running when the change event occurs in a particular cell or range. This is possible by setting conditions for the Target in your code.

In the above example, the ExampleCode macro will only be called when changes are made to cell A1.

Run VBA Macro from a Hyperlink

Did you know you can trigger your macros to run when you click on a hyperlink in Excel?

This is particular worksheet event method is worth its own mention!

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    If Target.Address = "B2" Then Call ExampleCode
End Sub

The above code will run every time you click the hyperlink in cell B2 in Sheet2.

The code will execute and then take you to the hyperlinked address!

Run VBA Macro from a Workbook Event

There is also the possibility to automatically run a macro based on workbook events such as when you open or close the file.

This is a great option to make sure a task is performed before you do anything else in your workbook.

Follow these steps to run a macro automatically when you open your Excel file.

  1. Select ThisWorkbook found in the Microsoft Excel Object folder of the VBE Projects.
  2. Select Workbook from the dropdown menu.
  3. Select Open from the event type dropdown menu.
Private Sub Workbook_Open()

End Sub

This will insert the above code into the code editor. You can then add any code inside which you want run when you open the file. You can also call any macro here with the Call YourMacroName single line of code.

Conclusions

VBA macros can be used to automate your tasks in Excel, so it’s important you know how to run them.

There are many methods to run your desired macros depending on your situation.

You can use the Excel ribbon, a keyboard shortcut, or a customized quick access command when you want to manually run a macro. Also, you can attach your macros to run from buttons in the workbook to make it more user friendly.

You might need to occasionally run your VBA macros while developing your solutions to test them. This can be done several ways in the visual basic editor.

You can even trigger your macros based on certain worksheet or workbook events for the ultimate in automation.

Are you using macros in Excel. Did you know all these methods to run your macros? Do you know any others? Let me know in the comments below!

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic

Introduction

This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).

Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.

  • In 1996, there were over 30 million users of Microsoft Excel (source).
  • Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.

We’re one big happy family!

In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.

Prerequisites

You don’t need any prior programming experience to understand this tutorial. However, you will need:

  • Basic to intermediate familiarity with Microsoft Excel
  • If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
  • A willingness to try new things

Learning Objectives

Over the course of this article, you will learn:

  1. What VBA is
  2. Why you would use VBA
  3. How to get set up in Excel to write VBA
  4. How to solve some real-world problems with VBA

Important Concepts

Here are some important concepts that you should be familiar with to fully understand this tutorial.

Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.

If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!

Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:

  • Subroutines: a group of VBA statements that performs one or more actions
  • Functions: a group of VBA statements that performs one or more actions and returns one or more values

Note: you can have functions operating inside of subroutines. You’ll see later.

Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.

Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.

For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.

What is VBA?

Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.

Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.

But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.

Pizza in a pizza oven

Yum.

Why use VBA in Excel?

Because wood-fired pizza is the best!

But seriously.

A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?

Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.

You should consider using VBA if you need to:

  • Automate repetitive tasks
  • Create easy ways for users to interact with your spreadsheets
  • Manipulate large amounts of data

Getting Set Up to Write VBA in Excel

Developer Tab

To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.

VBA developer tab

To add the Developer tab to the ribbon:

  1. On the File tab, go to Options > Customize Ribbon.
  2. Under Customize the Ribbon and under Main Tabs, select the Developer check box.

After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.

VBA Editor

Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.

VBA editor

Excel VBA Examples

First, let’s create a file for us to play around in.

  1. Open a new Excel file
  2. Save it as a macro-enabled workbook (. xlsm)
  3. Select the Developer tab
  4. Open the VBA Editor

Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.

Example #1: Display a Message when Users Open the Excel Workbook

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub

Save, close the workbook, and reopen the workbook. This dialog should display.

Welcome to XYZ notebook message example

Ta da!

How is it doing that?

Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:

  • Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
  • Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
  • By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
  • msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”

In short, this is a simple subroutine that contains a function.

When could I use this?

Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.

  • Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
  • Solution: create a user message that contains a concise answer to each of these frequently answered questions.

Real World Examples

  • Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
  • Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
  • Use the InputBox function to get information from the user

Example #2: Allow User to Execute another Procedure

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub

Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub

Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.

Now click the button. This message should display:

Process the XYZ report message example

Click “yes” or hit Enter.

Thanks for processing the XYZ report message example

Once again, tada!

Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first…

How is it doing that?

This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:

  • Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
  • Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
  • UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
  • Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
  • If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.

When could I use this?

This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.

For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.

  • Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
  • Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.

Real World Examples

  • Create a dialog box for user to automatically populate certain information across multiple sheets
  • Use the InputBox function to get information from the user, which is then populated across multiple sheets

Example #3: Add Numbers to a Range with a For-Next Loop

For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub

Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.

This should happen:

For-Next loop results

Etc, until the 100th row.

How is it doing that?

  • Dim X As Integer: declares the variable X as a data type of Integer.
  • For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
  • Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
  • Next X: this tells the loop to run again

When could I use this?

The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.

Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.

You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.

Real World Examples

  • Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
  • Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
  • Loop through each character in a string and extract all numbers
  • Randomly select a number of values from an array

Conclusion

Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.

  • What is VBA?
  • How do I get set up to start using VBA in Excel?
  • Why and when would you use VBA?
  • What are some problems I could solve with VBA?

If you have a fair idea of how to you could answer these questions, then this was successful.

Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.

Happy coding!

Learning Resources

  • Excel VBA Programming for Dummies, John Walkenbach
  • Get Started with VBA, Microsoft Documentation
  • Learning VBA in Excel, Lynda

A bit about me

I’m Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I’m continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Whether you’re new to Excel VBA or just want a refresher, this tutorial is for you. In 20 minutes (or less!), we’ll take you through the basics of working with VBA code. You’ll learn to write and run VBA code, use the macro recorder, and more! We also give you some common examples when working on VBA Excel. So, buckle up as we’re going to get started! 😉

What is VBA in Excel?

VBA stands for Visual Basic for Applications. It’s a programming language used to automate tasks in Microsoft Office products, including Excel, Word, and Outlook. With VBA Excel, you can write code to automate tasks, create custom functions, and even move data between Office programs.

This programming language was introduced with Excel 5.0 in 1993. It might be hard to believe that the Excel and VBA combo has been around for almost 30 years now. And as you can see, we’re still talking about it today! This means that this language is still popular among spreadsheet users—which makes sense considering what it offers and that few other spreadsheet apps can compete with this.

Why is VBA important?

VBA is important because of all the things it can do, but mainly its ability to automate mundane tasks that take a lot of time is particularly useful. As well as that, here are some common uses of VBA in Excel:

  • Create custom functions. If you find yourself using the same complex formula over and over again, you can save yourself some time by creating a custom function using VBA. 
  • Create custom add-ins for Excel. Add-ins are small programs that extend the functionality of Excel. You can, for example, create an add-in that allows you to apply formatting to selected cells, generate random numbers, apply formulas, or anything else you may want to improve productivity.
  • Simplify the data entry process. With Excel VBA, you can create custom forms that will simplify data entry and eliminate errors. You’ll be able to enter all information in one place with consistent formats. It’s easier for everyone involved. 
  • Automate tasks that you would otherwise have to do manually. Automating tedious, manual tasks with VBA Excel code is an easy way to save time and avoid mistakes. Here’s a common example. You might need to frequently update your spreadsheets by pulling data from various sources such as QuickBooks or Xero. However, doing this manually every day can prove costly in both efficiency and accuracy due to human error.

Are there no-code ways to automate workflows in Excel?

If you want to automate such processes without coding, Power Query is one of your best options. However, it’s not always ideal if any of your data sources isn’t supported by Power Query. 

In this case, try using third-party integration tools like Coupler.io, which is a solution to import data from different sources into Excel automatically. You can even set up a schedule to refresh your data (hourly, daily, monthly, etc.) to keep it always up-to-date.

Coupler.io allows you to pull data from CRM applications like Pipedrive, time-tracking tools like Clockify and many other apps and sources including Microsoft Excel. Check out all the available Excel integrations to choose the ones you need. So, you basically can automate data flow between your workbooks or even merge Excel files using it. 

Excel VBA programming: Before you get started

Before we get started with Excel VBA programming, let’s understand a few basic terminologies and how to open the Visual Basic Editor (VBE).

A few basic terminologies 

Here are a few terminologies we’ll be looking at in this article:

  • A macro is simply a procedure written in VBA Excel. You can write macros by using the macro recorder or write your own code. 
  • A module is where you will store your code. Think of it as a blank canvas where you can write whatever you want.
  • A procedure is an instruction or a set of instructions. The two main types of procedures are Sub procedure and Function procedure.
  • A Sub procedure (or Sub) is a procedure that only performs actions and does not return a value.
  • A Function procedure (or Function) is a procedure that returns a value.

How to open VBA editor in Excel

To use VBA in Excel, you first need to open the Visual Basic Editor (VBE) by simply pressing Alt+F11 on your keyboard. 

Alternatively, click on the Developer tab from the ribbon menu, then click on the Visual Basic button. If the Developer tab is not visible, see the section below on how to show the Developer tab in Excel.

1 The Developer tab in Excel

After the Visual Basic Editor is open, you’ll be able to find multiple sections described below:

2 The Visual Basic Editor VBE

  • Menu bar. This is the main menu of the VBE and contains various commands. Many of the commands have shortcut keys associated with them.
  • Code pane. This area is where the macro/code can be found. Here are all declaration variables, procedures, functions, etc.
  • Toolbar. It contains most of the useful commands that are used while codding. You can customize it by clicking View > Toolbars, then customize as you see fit. Most people just leave them as they are.
  • Project Explorer. The Project Explorer Window can usually be found on the top left side of the VBA Excel editor, showing a hierarchical list of open projects. This list contains Microsoft Excel Objects (Sheets and ThisWorkbook section), Forms (all User Forms created in the project), Modules (all macro modules), and Class Modules.
  • Properties Window. The Properties Window is where you can set all the properties for all objects from your application. The properties can be sorted alphabetically or by category.

How to show the Developer tab in Excel

The Developer tab is hidden by default in Excel, but you can easily show it if you need to access the features it contains. To do so, here’s a quick guide:

  • First, click on File > Options.
  • In the Excel Options dialog box, click on Customize Ribbon.
  • On the right pane, check the box next to Developer.
  • Click OK to save your changes and close the dialog box.

3 How to enable the Developer tab in Excel

Just that! Now when you open Excel, you will see the Developer tab listed among the other tabs at the top of the window.

How to use VBA in Excel

Most of the code people write in VBA are Sub and Function procedures. So, in this section, we’ll mostly learn about how to write, edit, and run them. 

How to write VBA code in Excel manually

To write VBA code manually, follow the steps below:

  • Create a new Excel workbook.
  • Press Alt+F11 to activate the VBE. 
  • Click Insert > Module in the menu bar.
  • Type manually or copy-paste the following code in the editor: 
Sub ShowHello()
 MsgBox "Hello, " & Application.UserName & "!"
End Sub

Function ShowCurrentTime()
 ShowCurrentTime = "Current time: " & Now
End Function

4 How to write VBA code in Excel

  • If you want, save the code by pressing Ctrl+S. The extension of the file needs to be XLSM because it contains a macro. 

Code explanation:

  • The ShowHello() is an example of a Sub procedure. Every Sub procedure starts with the keyword Sub and ends with an End Sub. 
  • The ShowCurrentTime() is an example of an Excel VBA Function procedure. Every Function procedure starts with the keyword Function and ends with an End Function.

How to run VBA code in Excel

Sub and Function procedures are run differently in Excel. Both can be executed in several ways, but we will cover only a few of them.

To execute an Excel VBA Function procedure: 

You can click the Run button in the VBE toolbar or simply press F5 for the same command. Excel executes the Sub procedure in which the cursor is located.

5 The Run button

Alternatively, you can execute Sub procedures from Excel by pressing the Macros button in the Developer tab:

6 Running a macro from Excel

To execute a Function procedure: 

You can use it in a worksheet or call it from another procedure (a Sub or another Function procedure). 

As an example, let’s see how to execute the ShowCurrentTime function by using it as a worksheet formula. To do that, simply type =ShowCurrentTime() in a cell, then press Enter. See the image below:

7 Calling a Function procedure

How to record VBA code in Excel 

Another way you can get code into a VBA module is by recording your actions using the Excel Macro Recorder. The result is always a Sub procedure. So, we cannot use this tool as an alternative method of creating functions — they must be manually entered by writing and editing the code ourselves.

Here is the step-by-step for recording a macro: 

  • Go to the Developer tab and click the Record Macro button.
  • In the Record Macro dialog box, enter a name for the macro. Optionally, you can enter a shortcut key, macro location, and description. 

8 The Record Macro dialog box

  • Click OK to start recording.
  • Perform all the actions that need to be recorded. For example, let’s just enter 1 to 10 from A1 to A10 manually:

9 Example macro

  • When you finish, click the Stop Recording button in the Developer tab.

How to edit recorded VBA code in Excel

After you record a macro, you may be curious to see what the code looks like. You might even wonder where your recorded macros are stored, right? Well, by default, they’re stored in a module. 

So, to view and edit recorded macros, first, you need to activate the VBE by pressing Alt+F11 on your keyboard. After that, double-click the new module created and locate the code you want to edit. 

For example, here is the AssignRowNumber macro we recorded previously:

Sub AssignRowNumber()
'
' AssignRowNumber Macro
' This procedure inserts row numbers to cells, 1 to 10.
'
' Keyboard Shortcut: Ctrl+Shift+M
'
    ActiveCell.FormulaR1C1 = "1"
    Range("A2").Select
    ActiveCell.FormulaR1C1 = "2"
    Range("A3").Select
    ActiveCell.FormulaR1C1 = "3"
    Range("A4").Select
    ActiveCell.FormulaR1C1 = "4"
    Range("A5").Select
    ActiveCell.FormulaR1C1 = "5"
    Range("A6").Select
    ActiveCell.FormulaR1C1 = "6"
    Range("A7").Select
    ActiveCell.FormulaR1C1 = "7"
    Range("A8").Select
    ActiveCell.FormulaR1C1 = "8"
    Range("A9").Select
    ActiveCell.FormulaR1C1 = "9"
    Range("A10").Select
    ActiveCell.FormulaR1C1 = "10"
End Sub

However, you may agree that the above code is not the best way to assign values to the cells. It selects a cell, assigns value as a formula, and then moves to the next cell. We can make the code more compact, readable, and dynamic using the following code:

Sub AssignRowNumber()
'
' AssignRowNumber Macro
' This procedure inserts row numbers to cells, 1 to 10.
'
' Keyboard Shortcut: Ctrl+Shift+M
'
 For i = 1 To 10
  ActiveSheet.Cells(i, 1).Value = i
 Next i

End Sub

In conclusion, the Macro Recorder is a great way to get into VBA programming. However, it can be complicated sometimes to understand the macro recorded. The good news is that recorded macros can be customized after they’re created, giving you even more control over what your program does and how it operates!

How to assign VBA code to a button in Excel

You can easily add a button to an Excel sheet and assign a macro to it. A few simple steps can do this.    

For example, let’s take the running ShowHello() Sub procedure one step further by executing it on a button click.

Here are the steps:

  • Click the Developer tab, then click Insert > Button (Form Control).

10 Inserting a button

  • Click and drag anywhere on the worksheet to create a button. 
  • In the Assign Macro dialog, select ShowHello, then click OK.

11 The Assign Macro dialog box

  • By default, a “Button 1” is created. Click the button’s text and type “Show Hello” to rename it.
  • To test the button, click on it. You’ll see a message box appear showing Hello to you 😉

12 How to assign a macro to a button the result

More VBA Excel examples 

This section contains several examples that demonstrate common VBA programming concepts. You may be able to use or adapt these pieces for your own needs.

Example #1: Looping through a range of cells

Many macros operate on each cell in a range, or they perform selected actions based on each cell’s value. These macros usually include a ForEach-Next loop that processes each cell in the range.

The following SUMODDNUMBERS function demonstrates how to loop through a range of cells to sum all the odd numbers.

Function SUMODDNUMBERS(range As range)
 Dim cell As range
 
 For Each cell In range
  If cell.Value Mod 2 = 1 Then
   SUMODDNUMBERS = SUMODDNUMBERS + cell.Value
  End If
 Next cell

End Function

To use the function, type =SUMODDNUMBERS() in a cell and input a range of cells in the parameter. See the screenshot below:

13 Excel VBA example Looping

Example #2: Conditional structure

The following example shows how to use a decision structure using a Select-Case statement. Many programmers like the Select-Case structure over If-Then-Else because the code looks more readable when checking multiple conditions. 

Sub ShowBudgetText()
    Dim Budget As Long
    Dim Result As String
    
    Budget = InputBox("Enter project budget: ")
    
    Select Case Budget
        Case 0 To 5000: Result = "LOW"
        Case 5001 To 10000: Result = "MEDIUM"
        Case Is > 10000: Result = "HIGH"
    End Select
    
    MsgBox "You have a " & Result & " budget."
End Sub

Code explanation:

The code prompts the user for a value, evaluates it, and then outputs a result. It evaluates the Budget variable and checks for three different cases (0–5000, 5001-10000, and greater than 10000). The Select-Case structure is exited as soon as VBA finds a TRUE case and executes the statements for that particular block.

Example #3: Error handling

You can’t always anticipate every error that might occur. But if possible, you should trap them to ensure your program doesn’t crash at runtime.

Below are the three methods of error handling in VBA. Each has its own benefits and drawbacks, so it’s important to choose the right one for your needs.

  • On Error Resume Next ignores any encountered errors and prevents the code from stopping.
  • On Error GoTo 0 stops the code on the line that causes the error and shows a message box describing the error.
  • On Error GoTo [Label] allows you to specify what you want to do with the errors.

Let’s see an example. We’ll add an On Error GoTo [Label] error handling method to our previous ShowBudgetText Sub. This will trap any type of runtime error and then display the error in a warning message box.

Sub ShowBudgetText()
    Dim Budget As Long
    Dim Result As String
    
    On Error GoTo ErrorHandler
    
    Budget = InputBox("Enter project budget: ")
    
    Select Case Budget
        Case 0 To 5000: Result = "LOW"
        Case 5001 To 10000: Result = "MEDIUM"
        Case Is > 10000: Result = "HIGH"
    End Select
    
    MsgBox "You have a " & Result & " budget."
    
ErrorHandler:
    MsgBox "Please enter a valid input.", vbExclamation

End Sub

5 Tips for mastering Excel VBA programming

Learning any new programming language can be daunting at first, but we hope this article has given you a good start in learning Excel VBA. 

In this last section, we’ve included five of our top tips that will help you on your journey to mastering the language:

  1. Start by learning the basics of programming. If you’re new to programming, it’s important to start with understanding what a variable is, various data types in VBA, how to use loops and conditions, etc. 
  2. Make use of online resources. Fortunately, there are plenty of resources available to help you learn the basics. Once you have a good understanding of programming fundamentals, you’ll be able to start taking advantage of Excel VBA’s more advanced features.
  3. Familiarize yourself with common Excel VBA objects and methods. Some of the most commonly used Excel VBA objects include Range, Worksheet, and Workbook. 
  4. Experiment with the Record Macro feature. This is a great way to get a feel for Excel VBA without having to write any code yourself. Simply record a macro and then edit the resulting code to customize it to your needs.
  5. Don’t forget to have fun! Excel VBA can be a powerful tool, but it’s also meant to be enjoyable. So relax and enjoy the process of learning something new.

Finally, thanks for reading, and have fun! 😊

  • Fitrianingrum Seto

    Senior analyst programmer

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

We can execute vba in excel by launching the excel application and running the visual basic for applications in the developer tab. This tutorial would teach us how to launch VBA in excel.

Figure 1: How to run macros in excel

Running VBA

  • To run vba, we will open a spreadsheet

Figure 2: VBA run macro

We will click on the developer option in the taskbar. We will click Visual Basic in the Code Group

Figure 3: Launching the VBA program

  • This will run the VBA on a separate page

Figure 4: VBA launched

  • We will click on insert and select module to begin writing a new vba code

Figure 5: New module for VBA code

  • We can now begin writing our code

Figure 6: Begin writing code

  • When we are through writing our code, we will click on run to execute the vba code on macro on the workbook.

Figure 7: VBA code written and ready to run

Instant Connection to an Expert through our Excelchat Service

Most of the time, the problem you will need to solve will be more complex than a simple application of a formula or function. If you want to save hours of research and frustration, try our live Excelchat service! Our Excel Experts are available 24/7 to answer any Excel question you may have. We guarantee a connection within 30 seconds and a customized solution within 20 minutes.

The first step to working with VBA in Excel is to get yourself familiarized with the Visual Basic Editor (also called the VBA Editor or VB Editor).

In this tutorial, I will cover all there is to know about the VBA Editor and some useful options that you should know when coding in Excel VBA.

What is Visual Basic Editor in Excel?

Visual Basic Editor is a separate application that is a part of Excel and opens whenever you open an Excel workbook. By default, it’s hidden and to access it, you need to activate it.

VB Editor is the place where you keep the VB code.

There are multiple ways you get the code in the VB Editor:

  1. When you record a macro, it automatically creates a new module in the VB Editor and inserts the code in that module.
  2. You can manually type VB code in the VB editor.
  3. You can copy a code from some other workbook or from the internet and paste it in the VB Editor.

Opening the VB Editor

There are various ways to open the Visual Basic Editor in Excel:

  1. Using a Keyboard Shortcut (easiest and fastest)
  2. Using the Developer Tab.
  3. Using the Worksheet Tabs.

Let’s go through each of these quickly.

Keyboard Shortcut to Open the Visual Basic Editor

The easiest way to open the Visual Basic editor is to use the keyboard shortcut – ALT + F11 (hold the ALT key and press the F11 key).

Keyboard Shortcut to open Visual Basic Editor in Excel

As soon as you do this, it will open a separate window for the Visual Basic editor.

This shortcut works as a toggle, so when you use it again, it will take you back to the Excel application (without closing the VB Editor).

The shortcut for the Mac version is Opt + F11 or Fn + Opt + F11

Using the Developer Tab

To open the Visual Basic Editor from the ribbon:

  1. Click the Developer tab (if you don’t see a developer tab, read this on how to get it).
  2. In the Code group, click on Visual Basic.

Visual Basic Editor button in the ribbon

Using the Worksheet Tab

This is a less used method to open the Vb Editor.

Go to any of the worksheet tabs, right-click, and select ‘View Code’.

View code to open the VB Editor

This method wouldn’t just open the VB Editor, it will also take you to the code window for that worksheet object.

This is useful when you want to write code that works only for a specific worksheet. This is usually the case with worksheet events.

Anatomy of the Visual Basic Editor in Excel

When you open the VB Editor for the first time, it may look a bit overwhelming.

There are different options and sections that may seem completely new at first.

Also, it still has an old Excel 97 days look. While Excel has improved tremendously in design and usability over the years, the VB Editor has not seen any change in the way it looks.

In this section, I will take you through the different parts of the Visual Basic Editor application.

Note: When I started using VBA years ago, I was quite overwhelmed with all these new options and windows. But as you get used to working with VBA, you would get comfortable with most of these. And most of the time, you’ll not be required to use all the options, only a hand full.

Below is an image of the different components of the VB Editor. These are then described in detail in the below sections of this tutorial.

Different Parts of the VB Editor in Excel

Now let’s quickly go through each of these components and understand what it does:

Menu Bar

This is where you have all the options that you can use in the VB Editor. It is similar to the Excel ribbon where you have tabs and options with each tab.

You can explore the available options by clicking on each of the menu element.

You will notice that most of the options in VB Editor have keyboard shortcuts mentioned next to it. Once you get used to a few keyboard shortcuts, working with the VB Editor becomes really easy.

Tool Bar

By default, there is a toolbar in the VB Editor which has some useful options that you’re likely to need most often. This is just like the Quick Access Toolbar in Excel. It gives you quick access to some of the useful options.

You can customize it a little by removing or adding options to it (by clicking on the small downward pointing arrow at the end of the toolbar).

Add or Remove options in the toolbar

In most cases, the default toolbar is all you need when working with the VB Editor.

You can move the toolbar above the menu bar by clicking on the three gray dots (at the beginning of the toolbar) and dragging it above the menu bar.

Note: There are four toolbars in the VB Editor – Standard, Debug, Edit, and User form. What you see in the image above (which is also the default) is the standard toolbar. You can access other toolbars by going to the View option and hovering the cursor on the Toolbars option. You can add one or more toolbars to the VB Editor if you want.

Project Explorer

Project Explorer is a window on the left that shows all the objects currently open in Excel.

When you’re working with Excel, every workbook or add-in that is open is a project. And each of these projects can have a collection of objects in it.

For example, in the below image, the Project Explorer shows the two workbooks that are open (Book1 and Book2) and the objects in each workbook (worksheets, ThisWorkbook, and Module in Book1).

There is a plus icon to the left of objects that you can use to collapse the list of objects or expand and see the complete list of objects.

Project Explorer in Excel VBA Editor

The following objects can be a part of the Project Explorer:

  1. All open Workbooks – within each workbook (which is also called a project), you can have the following objects:
    • Worksheet object for each worksheet in the workbook
    • ThisWorkbook object which represents the workbook itself
    • Chartsheet object for each chart sheet (these are not as common as worksheets)
    • Modules – This is where the code that is generated with a macro recorder goes. You can also write or copy-paste VBA code here.
  2. All open Add-ins

Consider the Project Explorer as a place that outlines all the objects open in Excel at the given time.

The keyboard shortcut to open the Project Explorer is Control + R (hold the control key and then press R). To close it, simply click the close icon at the top right of the Project Explorer window.

Note: For every object in Project Explorer, there is a code window in which you can write the code (or copy and paste it from somewhere). The code window appears when you double click on the object.

Properties Window

Properties window is where you get to see the properties of the select object. If you don’t have the Properties window already, you can get it by using the keyboard shortcut F4 (or go to the View tab and click Properties window).

Properties window is a floating window which you can dock in the VB Editor. In the below example, I have docked it just below the Project Explorer.

Properties Window is docked below Project Explorer

Properties window allows us to change the properties of a selected object. For example, if I want to make a worksheet hidden (or very hidden), I can do that by changing the Visible Property of the selected worksheet object.

Changing the Visible Property of the Worksheet in Properties Window

Related: Hiding a Worksheet in Excel (that can not be un-hidden easily)

Code Window

There is a code window for each object that is listed in the Project Explorer. You can open the code window for an object by double-clicking on it in the Project Explorer area.

Code window is where you’ll write your code or copy paste a code from somewhere else.

When you record a macro, the code for it goes into the code window of a module. Excel automatically inserts a module to place the code in it when recording a macro.

Related: How to Run a Macro (VBA Code) in Excel.

Immediate Window

The Immediate window is mostly used when debugging code. One way I use the Immediate window is by using a Print.Debug statement within the code and then run the code.

It helps me to debug the code and determine where my code gets stuck. If I get the result of Print.Debug in the immediate window, I know the code worked at least till that line.

If you’re new to VBA coding, it may take you some time to be able to use the immediate window for debugging.

By default, the immediate window is not visible in the VB Editor. You can get it by using the keyboard shortcut Control + G (or can go to the View tab and click on ‘Immediate Window’).

Where to Add Code in the VB Editor

I hope you now have a basic understanding of what VB Editor is and what all parts it has.

In this section of this tutorial, I will show you where to add a VBA code in the Visual Basic Editor.

There are two places where you can add the VBA code in Excel:

  1. The code window for an object. These objects can be a workbook, worksheet, User Form, etc.
  2. The code window of a module.

Module Code Window Vs Object Code Window

Let me first quickly clear the difference between adding a code in a module vs adding a code in an object code window.

When you add a code to any of the objects, it’s dependent on some action of that object that will trigger that code. For example, if you want to unhide all the worksheets in a workbook as soon as you open that workbook, then the code would go in the ThisWorkbook object (which represents the workbook).

The trigger, in this case, is opening the workbook.

Similarly, if you want to protect a worksheet as soon as some other worksheet is activated, the code for that would go in the worksheet code window.

These triggers are called events and you can associate a code to be executed when an event occurs.

Related: Learn more about Events in VBA.

On the contrary, the code in the module needs to be executed either manually (or it can be called from other subroutines as well).

When you record a macro, Excel automatically creates a module and inserts the recorded macro code in it. Now if you have to run this code, you need to manually execute the macro.

Adding VBA Code in Module

While recording a macro automatically creates a module and inserts the code in it, there are some limitations when using a macro recorder. For example, it can not use loops or If Then Else conditions.

In such cases, it’s better to either copy and paste the code manually or write the code yourself.

A module can be used to hold the following types of VBA codes:

  1. Declarations: You can declare variables in a module. Declaring variables allows you to specify what type of data a variable can hold. You can declare a variable for a sub-routine only or for all sub-routines in the module (or all modules)
  2. Subroutines (Procedures): This is the code that has the steps you want VBA to perform.
  3. Function Procedures: This is a code that returns a single value and you can use it to create custom functions (also called User Defined Functions or UDFs in VBA)

By default, a module is not a part of the workbook. You need to insert it first before using it.

Adding a Module in the VB Editor

Below are the steps to add a module:

  1. Right-click on any object of the workbook (in which you want the module).Right click on any object
  2. Hover the cursor on the Insert option.
  3. Click on Module.Click on Module

This would instantly create a folder called Module and insert an object called Module 1. If you already have a module inserted, the above steps would insert another module.

Inserted Module in the VB Editor

Once the module is inserted, you can double click on the module object in the Project Explorer and it will open the code window for it.

Now you can copy-paste the code or write it yourself.

Removing the Module

Below are the steps to remove a module in Excel VBA:

  1. Right-click on the module that you want to remove.
  2. Click on Remove Module option.Remove Module for a Project in the VB Editor
  3. In the dialog box that opens, click on No.Prompt before a module is deleted

Note: You can export a module before removing it. It gets saved as a .bas file and you can import it in some other project. To export a module, right-click on the module and click on ‘Export file’.

Adding Code to the Object Code Window

To open the code window for an object, simply double-click on it.

When it opens, you can enter the code manually or copy-paste the code from other modules or from the internet.

Note that some of the objects allow you to choose the event for which you want to write the code.

For example, if you want to write a code for something to happen when selection is changed in the worksheet, you need to first select worksheets from the drop-down at the top left of the code window and then select the change event from the drop-down on the right.

Selection Change Event in VBA Code Window

Note: These events are specific to the object. When you open the code window for a workbook, you will see the events related to the workbook object. When you open the code window for a worksheet, you will see the events related to the worksheet object.

Customizing the VB Editor

While the default settings of the Visual Basic Editor are good enough for most users, it does allow you to further customize the interface and a few functionalities.

In this section of the tutorial, I will show you all the options you have when customizing the VB Editor.

To customize the VB Editor environment, click Tools in the menu bar and then click on Options.

This would open the Options dialog box which will give you all the customization options in the VB Editor. The ‘Options’ dialog box has four tabs (as shown below) that have various customizations options for the Visual Basic Editor.

Options to customize the Vb Editor

Let’s quickly go through each of these tabs and the important options in each.

Editor Tab

While the inbuilt settings work fine in most cases, let me still go through the options in this tab.

As you get more proficient working with VBA in Excel, you may want to customize the VB Editor using some of these options.

Auto Syntax Check

When working with VBA in Excel, as soon as you make a syntax error, you will be greeted by a pop-up dialog box (with some description about the error). Something as shown below:

Auto Syntax Check in Visual Basic Editor Options

If you disable this option, this pop-up box will not appear even when you make a syntax error. However, there would be a change in color in the code text to indicate that there is an error.

If you’re a beginner, I recommend you keep this option enabled. As you get more experienced with coding, you may start finding these pop-up boxes irritating, and then you can disable this option.

Require Variable Declaration

This is one option I recommend enabling.

When you’re working with VBA, you would be using variables to hold different data types and objects.

When you enable this option, it automatically inserts the ‘Option Explicit’ statement at the top of the code window. This forces you to declare all the variables that you’re using in your code. If you don’t declare a variable and try to execute the code, it will show an error (as shown below).

Varibale Not Declared Error in Excel VBA

In the above case, I used the variable Var, but I didn’t declare it. So when I try to run the code, it shows an error.

This option is quite useful when you have a lot of variables. It often helps me find misspelled variables names as they are considered as undeclared and an error is shown.

Note: When you enable this option, it does not impact the existing modules.

Auto List Member

This option is quite useful as it helps you get a list of properties of methods for an object.

For example, if I want to delete a worksheet (Sheet1), I need to use the line Sheet1.Delete.

While I am typing the code, as soon as I type the dot, it will show me all the methods and properties associated with the Worksheet object (as shown below).

Autolist Member Option in VB Editor

Auto list feature is great as it allows you to:

  • Quickly select the property and method from the list and saves time
  • Shows you all the properties and methods which you may not be aware of
  • Avoid making spelling errors

This option is enabled by default and I recommend keeping it that way.

Auto Quick Info Options

When you type a function in Excel worksheet, it shows you some information about the function – such as the arguments it takes.

Similarly, when you type a function in VBA, it shows you some information (as shown below). But for that to happen, you need to make sure the Auto Quick Info option is enabled (which it is by default).

Auto Quick Info Option in VB Editor

Auto Data Tips Options

When you’re going through your code line by line and place your cursor above a variable name, it will show you the value of the variable.

I find it quite useful when debugging the code or going through the code line by line which has loops in it.

Auto Data Tips Option in Visual Basic Editor Options

In the above example, as soon as I put the cursor over the variable (var), it shows the value it holds.

This option is enabled by default and I recommend you keep it that way.

Auto Indent

Since VBA codes can get long and messy, using indentation increases the readability of the code.

When writing code, you can indent using the tab key.

This option ensures that when you are done with the indented line and hit enter, the next line doesn’t start from the very beginning, but has the same indentation as the previous line.

Indentation enabled in the VB Editor code windows

In the above example, after I write the Debug.Print line and hit enter, it will start right below it (with the same indentation level).

I find this option useful and turning this off would mean manually indenting each line in a block of code that I want indented.

You can change the indentation value if you want. I keep it at the default value.

Drag and Drop Text Editing

When this option is enabled, it allows you to select a block of code and drag and drop it.

It saves time as you don’t have to first cut and then paste it. You can simply select and drag it.

This option is enabled by default and I recommend you keep it that way.

Default to Full Module View

When this option is enabled, you will be able to see all the procedures in a module in one single scrollable list.

If you disable this option, you will only be able to see one module at a time. You will have to make a selection of the module you want to see from the drop-down at the top right of the code window.

This option is enabled by default and I recommend keeping it that way.

One reason you may want to disable it when you have multiple procedures that are huge and scrolling across these is taking time, or when you have a lot of procedures and you want to quickly find it instead of wasting time in scrolling.

Procedure Separator

When this option is enabled, you will see a line (a kind of divider) between two procedures.

I find this useful as it visually shows when one procedure ends and the other one starts.

Procedure Separator Option in VB Editor

It’s enabled by default and I recommend keeping it that way.

Editor Format Tab

With the options in the Editor Format tab, you can customize the way your code looks in the code window.

Personally, I keep all the default options as I am fine with it. If you want, you can tweak this based on your preference.

To make a change, you need to first select an option in the Code Colors box. Once an option is selected, you can modify the foreground, background, and indicator color for it.

The font type and font size can also be set in this tab. It’s recommended to use a fixed-width font such as Courier New, as it makes the code more readable.

Note that the font type and size setting will remain the same for all code types (i.e., all the code types shown in the code color box).

Below is an image where I have selected Breakpoint, and I can change the formatting of it.

Editor Format Options in VB Editor

Note: The Margin Indicator Bar option when enabled shows a little margin bar to the left of the code. It’s helpful as it shows useful indicators when executing the code. In the above example, when you set a breakpoint, it will automatically show a red dot to the left of the line in the margin bar. Alternatively, to set a breakpoint, you can simply click on the margin bar on the left of the code line that you want as the breakpoint.

By default, Margin Indicator Bar is enabled and I recommend keeping it that way.

One of my VBA course students found this customization options useful and she was color blind. Using the options here, she was able to set the color and formats that made it easy for her to work with VBA.

General Tab

The General tab has many options but you don’t need to change any of it.

I recommend you keep all the options as is.

One important option to know about in this tab is Error Handling.

By default, ‘Break on Unhandled Errors’ is selected and I recommend keeping it that way.

This option means that if your code encounters an error, and you have not handled that error in your code already, then it will break and stop. But if you have addressed the error (such as by using On Error Resume Next or On Error Goto options), then it will not break (as the errors are not unhandled).

Docking Tab

In this tab, you can specify which windows you want to get docked.

Docking means that you can fix the position of a window (such as project explorer or the Properties window) so that it doesn’t float around and you can view all the different windows at the same time.

If you don’t dock, you will be able to view one window at a time in full-screen mode and will have to switch to the other one.

I recommend keeping the default settings.

Other Excel tutorials you may like:

  • How to Remove Macros From an Excel Workbook
  • Comments in Excel VBA (Add, Remove, Block Commenting)
  • Using Active Cell in VBA in Excel (Examples)

VBA is an excellent tool in Microsoft Office suite, including MS Excel application. It can assist you to accomplish a lot of tasks not supported by the native features in Excel. Now, in this article, we will teach you to run VBA code in Excel step by step.

If you intend to write some VBA codes to achieve some of your requirements, you have to firstly figure out how to run VBA code in your Excel. Now, thereinafter, we will use MS Excel 2010 for an instance to show the detailed steps, including how to enable macro, trigger VBA editor and several means to run macro, etc.

Step 1: Show “Developer” Ribbon

  1. First off, launch Excel application.
  2. Then, go to “File” menu and click “Options”.Access "Excel Options"
  3. In the popup “Excel Options” window, turn to “Customize Ribbon” tab.
  4. Next, in the right side, find and check the “Developer” option.Enable "Developer" Ribbon
  5. Finally, click “OK” to enable the modifications.

Step 2: Change Macro Security Settings

Since Excel comes with macro auto disabled in security settings, you need to first change the settings by following the steps below:

  1. At first, in Excel main window, switch to “Developer” ribbon.
  2. Then, click “Macro Security” button in “Code” group.
  3. Next, in the new window, select “Disable all macros except digitally signed macros” or “Enable all macros” option to your liking.Change Macro Security Settings
  4. Lastly, click “OK” to save the changes.

Step 3: Trigger Excel VBA Editor

Excel VBA editor is the place where you put the code. You can get access to it by 2 means.

  1. On “Developer” tab, click the “Visual Basic” button in “Code” group.Trigger Excel VBA Editor
  2. Directly press “Alt + F11” key shortcuts to bring up “Microsoft Visual Basic for Applications” window.

Step 4: Add VBA Code

After entering Excel VBA editor, you need to add your code into either a project or a module.

1. Put Code into Existing Project

As you can see, under expanded “Microsoft Excel Objects” folder, you can see the existing projects, including the projects for each worksheet and the one for the current workbook called “ThisWorkbook”.Existing Projects

  1. To begin with, double click on a project to open its window.
  2. Then, put the code into it.Put Code in Project

2. Put Code into Module

Besides, you can add code to a module by the following steps.

  1. In the first place, click “Insert” button in toolbar.
  2. From the drop down list, select “Module”.Insert Module
  3. Then, in the new module, you can put your code.

Step 5: Run VBA Code

1. Run Macro in VBA Editor

To run VBA in the “Microsoft Visual Basic for Applications” window, you can just press “F5” key button or click the “Run” icon in the toolbar.Run Macro

2. Run Macro through Quick Access Toolbar (QAT)

Moreover, you can add macro to Quick Access Toolbar and run it through QAT by the steps below.

  1. At the outset, go to “File” > “Options”.
  2. In the popup window, access “Quick Access Toolbar” tab.
  3. Then, select “Macros” from the list of “Choose commands from”.Choose Commands from "Macros"
  4. Next, choose the macro in the left side.
  5. Later, click “Add” button in center.Add Macro to Quick Access Toolbar
  6. After that, click “OK” to save the changes to Quick Access Toolbar.
  7. Finally, in the main Excel window, to run this macro, you can click the macro button in Quick Access Toolbar, as shown in the following screenshot.Run Macro Through Quick Access Toolbar

3. Run Macro through Ribbon

In addition, like Quick Access Toolbar, you can add and run macro in ribbon.

  1. For a start, access “File” menu and hit “Options”.
  2. In “Excel Options”, go to “Customize Ribbon”.
  3. Then, create a new group on “Home” tab by “New Group”.
  4. Optionally, you can rename this group by “Rename…” button.Create Custom Group in Ribbon
  5. Subsequently, select “Macros” in the list of “Choose commands from”.
  6. After that, pitch on the desired macro in the left side.
  7. Next, click the “Add” button to add this macro to the new group.Add Macro to Custom Group in Ribbon
  8. Eventually, click “OK” to save options.
  9. Since then, to run this macro, you can click the newly added macro button in ribbon.Run Macro in Ribbon

Author Introduction:

Shirley Zhang is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including mdf recovery and outlook repair software products. For more information visit www.datanumen.com

Понравилась статья? Поделить с друзьями:
  • Execute function in excel
  • Exe запускается как word
  • Excuse me how is this word pronounce
  • Exclusive or in excel
  • Excite word of the day