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:
- What VBA is
- Why you would use VBA
- How to get set up in Excel to write VBA
- 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.
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.
To add the Developer tab to the ribbon:
- On the File tab, go to Options > Customize Ribbon.
- 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.
Excel VBA Examples
First, let’s create a file for us to play around in.
- Open a new Excel file
- Save it as a macro-enabled workbook (. xlsm)
- Select the Developer tab
- 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.
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:
Click “yes” or hit Enter.
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:
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
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:
- When you record a macro, it automatically creates a new module in the VB Editor and inserts the code in that module.
- You can manually type VB code in the VB editor.
- 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:
- Using a Keyboard Shortcut (easiest and fastest)
- Using the Developer Tab.
- 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).
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:
- Click the Developer tab (if you don’t see a developer tab, read this on how to get it).
- In the Code group, click on Visual Basic.
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’.
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.
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).
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.
The following objects can be a part of the Project Explorer:
- 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.
- 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 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.
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:
- The code window for an object. These objects can be a workbook, worksheet, User Form, etc.
- 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:
- 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)
- Subroutines (Procedures): This is the code that has the steps you want VBA to perform.
- 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:
- Right-click on any object of the workbook (in which you want the module).
- Hover the cursor on the Insert option.
- 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.
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:
- Right-click on the module that you want to remove.
- Click on Remove Module option.
- In the dialog box that opens, click on No.
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.
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.
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:
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).
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).
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 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.
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.
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.
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.
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)
Microsoft Excel enables users to automate features and commands using macros and Visual Basic for Applications (VBA) scripting. VBA is the programming language Excel uses to create macros. It will also execute automated commands based on specific conditions.
Macros are a series of pre-recorded commands. They run automatically when a specific command is given. If you have tasks in Microsoft Excel that you repeatedly do, such as accounting, project management, or payroll, automating these processes can save a lot of time.
Under the Developer tab on the Ribbon in Excel, users can record mouse clicks and keystrokes (macros). However, some functions require more in-depth scripting than macros can provide. This is where VBA scripting becomes a huge benefit. It allows users to create more complex scripts.
In this article, we will explain the following:
- Enabling Scripts & Macros
- How to Create a Macro in Excel
- Specific Example of a Macro
- Learn More About VBA
- Create a Button to Get Started with VBA
- Add Code to Give the Button Functionality
- Did it Work?
Enabling Scripts & Macros
Before you can create macros or VBA scripts in Excel, you must enable the Developer tab on the Ribbon menu. The Developer tab is not enabled by default. To enable it:
- Open an Excel worksheet.
- Click on File > Options > Customize Ribbon.
- Put a tick in the box next to Developer.
- Click on the Developer tab from the Ribbon menu.
- Next, click on Macro Security and tick the box next to Enable all macros (not recommended; potentially dangerous code can run).
- Then click OK.
The reason macros are not turned on by default and come with a warning is that they are computer code that could contain malware.
Make sure the document is from a trusted source if you are working on a shared project in Excel and other Microsoft programs.
When you are done using your scripts and macros, disable all macros to prevent potentially malicious code from infecting other documents.
All the actions you take in Excel while recording a macro are added to it.
- From the Developer tab, click on Record Macro.
- Enter a Macro name, a Shortcut key, and a Description. Macro names must begin with a letter and can’t have any spaces. The shortcut key must be a letter.
Decide where you want to store the macro from the following options:
- Personal Macro Workbook: This will create a hidden Excel document with stored macros to be used with any Excel documents.
- New Workbook: Will create a new Excel document to store the created macros.
- This Workbook: This will only be applied to the document you are currently editing.
When done, click OK.
- Run through the actions you want to automate. When you are finished, click Stop Recording.
- When you want to access your macro, use the keyboard shortcut you gave it.
Specific Example Of a Macro
Let’s start with a simple spreadsheet for customers and how much they owe. We will begin by creating a macro to format the worksheet.
Let’s assume that you decide that all spreadsheets should use a different format such as putting first and last name in separate columns.
You can manually change this. Or you can create a program using a macro to automatically format it correctly for you.
Record The Macro
- Click on Record Macro. Let’s call it Format_Customer_Data and click OK.
- To get the formatting we want, we will change the first column name to First Name.
- Then insert a column next to A and call it Last Name.
- Highlight all the names in the first column (which still include first and last name), and click on Data from the ribbon navigation.
- Click on Text to Columns.
- Tick Delimited > Next > Separate by Space > Next > Finish. See screenshot below and how the first and last names were separated by the process above.
- To format the Balance Due field, highlight the amounts. Click on Home > Conditional Formatting > Highlight Cell Rules > Greater Than > 0.
This will highlight the cells that have a balance due. We added a few customers with no balance due to further illustrate the formatting.
- Go back to Developer and click Stop Recording.
Apply The Macro
Let’s start with the original spreadsheet before we recorded the macro to format it correctly. Click on Macros, select and Run the macro you just created.
When you run a macro, all the formatting is done for you. This macro we just created is stored in the Visual Basic Editor.
Users can run macros in several different ways. Read Run a macro to learn more.
Learn More About VBA
To learn about VBA, click on Macro from the Developer tab. Find one you have created and click Edit.
The code you see in the box above is what was created when you recorded your macro.
It is also what you will run when you want to format other customer payment spreadsheets in the same way.
Create a Button To Get Started With VBA
Using the same spreadsheet above with customers and how much they owe, let’s create a currency converter.
- To insert a button element, navigate to the Developer tab.
- Select ActiveX Command Button from the dropdown next to Insert in the Controls section.
- Drag the button anywhere on the spreadsheet so you can easily access it and change it later if you want.
- To attach the code, right-click on the button and select Properties. We will keep the Name as CommandButton and the Caption to Convert (this is the button text).
Add Code To Give The Button Functionality
VBA coding doesn’t take place in the Excel interface. It is done in a separate environment.
- Go to the Developer tab and make sure Design Mode is active.
- To access the code of the button we just created, right-click on it and select View Code.
- Looking at the code in the screenshot below, notice the beginning (Private Sub) and end (End Sub) of the code is already there.
- The code below will drive the currency conversion procedure.
ActiveCell.Value = (ActiveCell * 1.28)
Our purpose in this section is to convert the currency in our spreadsheet. The script above reflects the exchange rate from GBP to USD. The new value of a cell will be what is currently there multiplied by 1.28.
The screenshot below shows you how the code looks in the VBA window after you insert it .
- Go to File in the top navigation and click on Close and Return to Microsoft Excel to return to the main Excel interface.
Did It Work?
Before you can test your code, you must first disable Design Mode (click on it) to avoid further modifications and give the button functionality.
- Type any number into your spreadsheet and then click the Convert button. If the value of your number increases by approximately one-quarter, it worked.
For this example, I put the number 4 into a cell. After clicking Convert, the number changed to 5.12. Since 4 times 1.28 is 5.12, the code was carried out correctly.
Now that you understand how to create a macro or script in Excel, you can use them to automate a multitude of actions in Excel.
Microsoft Excel VBA feature is a powerful interface tool that enables a user to automate tasks in a workbook. It is a programming language that helps excel users write their codes and even review the recorded macros they saved. In short, for a user to be a master of Excel’s VBA, they have to get used to its coding processes.
How do I open VBA? Any new beginner in Excel’s VBA Editor may find it daunting. But this should not be the case as the feature is user-friendly, and anyone can get the hang of it. This article focuses on addressing such doubts concerning VBA. Please read the article below to learn step-by-step how to open the Visual Basic Editor (VBA) in Excel.
Enabling the Developer tab in Excel
To use VBA, a user has first to enable the Developers tab in their Excel workbook. The tab has several groups and features to enhance how a user creates their worksheets. It allows one to open the VBA editor and create Form and ActiveX controls like checkboxes, buttons, and macros. Sometimes, the tab may already be available in the main menu ribbon of a worksheet. If not, here are the steps to follow to enable it;
1. In your open workbook, click on the File menu tab.
2. Click on the Excel Options button to display a dialog box.
3. On the given options on the left of the open dialog box, click on the ‘Customize Ribbon option.
4. Here, you will find two partitions, right and left.
5. Under Choose Command from on the left side of the dialog box, click on the drop-down arrow and select Popular Commands.
6. Under Customize the Ribbon on the right side of the dialog box, select Main Tabs from the drop-down list.
7. in the right panel, check the Developers checkbox if it is not already selected.
8. Click Ok to enable the tab and return to your open workbook. The main ribbon will have an additional visible tab marked as ‘Developer.’
Steps to follow to open VBA
After enabling the Developer tab, it is easy to open the VBA feature in Excel.
1. To open the feature, click on the Developers tab and select Visual Basic to display the’ Microsoft Visual Basic’ window.
Here is the Microsoft visual basic window
2. In cases where you want to use keyboard shortcuts to open the VBA window, press on Alt + F11 keys.
Both options above will open the Visual Basic Editor window in your Excel workbook. From here, you can create and even edit your macros, buttons, and codes.
Conclusion
Opening a VBA editor in Excel should no longer be a daunting task with the steps mentioned above. Using those steps will enable you to access the VBA editor and create your macros to allow you to complete tasks on time.
Note that;
Despite VBA being a powerful tool, it can also be harmful when used the wrong way. Any macro created should be saved in the appropriate files due to security risks. Some malicious writers may create dangerous macro codes as viruses to target an individual or a company’s data. Any macro-enabled document should be saved as an ‘Excel Macro-Enabled Workbook. Make sure to have permissions from your organization or a different person’s computer to run macros on their machines.
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
- First off, launch Excel application.
- Then, go to “File” menu and click “Options”.
- In the popup “Excel Options” window, turn to “Customize Ribbon” tab.
- Next, in the right side, find and check the “Developer” option.
- 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:
- At first, in Excel main window, switch to “Developer” ribbon.
- Then, click “Macro Security” button in “Code” group.
- Next, in the new window, select “Disable all macros except digitally signed macros” or “Enable all macros” option to your liking.
- 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.
- On “Developer” tab, click the “Visual Basic” button in “Code” group.
- 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”.
- To begin with, double click on a project to open its window.
- Then, put the code into it.
2. Put Code into Module
Besides, you can add code to a module by the following steps.
- In the first place, click “Insert” button in toolbar.
- From the drop down list, select “Module”.
- 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.
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.
- At the outset, go to “File” > “Options”.
- In the popup window, access “Quick Access Toolbar” tab.
- Then, select “Macros” from the list of “Choose commands from”.
- Next, choose the macro in the left side.
- Later, click “Add” button in center.
- After that, click “OK” to save the changes to Quick Access Toolbar.
- 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.
3. Run Macro through Ribbon
In addition, like Quick Access Toolbar, you can add and run macro in ribbon.
- For a start, access “File” menu and hit “Options”.
- In “Excel Options”, go to “Customize Ribbon”.
- Then, create a new group on “Home” tab by “New Group”.
- Optionally, you can rename this group by “Rename…” button.
- Subsequently, select “Macros” in the list of “Choose commands from”.
- After that, pitch on the desired macro in the left side.
- Next, click the “Add” button to add this macro to the new group.
- Eventually, click “OK” to save options.
- Since then, to run this macro, you can click the newly added macro button 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