VBA (Visual Basic for Applications) is a programming language that empowers you to automate almost every in Excel. With VBA, you can refer to the Excel Objects and use the properties, methods, and events associated with them. For example, you can create a pivot table, insert a chart, and show a message box to the user using a macro.
The crazy thing is:
For all the tasks which you perform manually in minutes, VBA can do it in seconds, with a single click, with the same accuracy. Even you can write VBA codes that can run automatically when you open a document, a workbook, or even at a specific time.
Let me show you a real-life example:
Every morning when I go to the office, the first thing I need to do is to create a pivot table for the month-to-date sales and present it to my boss. This includes the same steps, every day. But when I realized that I can use VBA to create a pivot table and insert it in a single click, it saved me 5 minutes every day.
Note: VBA is one of the Advanced Excel Skills.
How VBA Works
VBA is an Object-Oriented Language and as an object-oriented language, in VBA, we structure our codes in a way where we are using objects and then defining their properties.
In simple words, first, we define the object and then the activity which we want to perform. There are objects, collections, methods, and properties which you can use in VBA to write your code.
[icon name=”bell” class=””] Don’t miss this: Let’s say you want to tell someone to open a box. The words you will use would be “Open the Box”. It’s plain English, Right? But when it comes to VBA and writing a macro this will be:
Box.Open
As you can see, the above code is started with the box which is our object here, and then we have used the method “Open” for it. Let’s go a bit specific, let say if you want to open the box which is RED in color. And for this the code will be:
Boxes(“Red”).Open
In the above code, boxes are the collection, and open is the method. If you have multiple boxes we are defining a specific box here. Here’s another way:
Box(“Red”).Unlock = True
In the above code, again boxes are the collection, and Unlock is the property that is set to TRUE.
What is VBA used for in Excel?
In Excel, you can use VBA for different things. Here are a few:
- Enter Data: You can enter data in a cell, range of cells. You can also copy and paste data from one section to another.
- Task Automation: You can automate tasks that want you to spend a lot of time. The best example I can give is using a macro to create a pivot table.
- Create a Custom Excel Function: With VBA, you can also create a Custom User Defined Function and use it in the worksheet.
- Create Add-Ins: In Excel, you can convert your VBA codes into add-ins and share them with others as well.
- Integrate with other Microsoft Applications: You can also integrate Excel with other Microsoft applications. Like, you can enter data into a text file.
Excel Programming Fundamentals
A procedure in VBA is a set of codes or a single line of code that performs a specific activity.
- SUB: Sub procedure can perform actions but doesn’t return a value (but you can use an object to get that value).
- Function: With the help of the Function procedure, you create your function, which you can use in the worksheet or the other SUB and FUNCTION procedures (See this: VBA Function).
2. Variables and Constants
You need variables and constants to use values in the code multiple times.
- Variable: A Variable can store a value, it has a name, you need to define its data type, and you can change the value it stores. As the name suggests, “VARIABLE” has no fixed value. It is like a storage box that is stored in the system.
- Constant: A constant also can store a value, but you can’t change the value during the execution of the code.
3. Data Types
You need to declare the data type for VARIABLES and CONSTANTS.
When you specify the data type for a variable or a constant, it ensures the validity of your data. If you omit the data type, VBA applies the Variant data type to your variable (it’s the most flexible), VBA won’t guess what the data type should be.
Tip: VBA Option Explicit
4. Objects, Properties, and Methods
Visual Basic for Applications is an Object-Oriented language, and to make the best out of it; you need to understand Excel Objects.
The workbook you use in Excel has different objects, and with all those objects, there are several properties that you can access and methods that you can use.
5. Events
Whenever you do something in Excel, that’s an event: enter a value in a cell, insert a new worksheet, or insert a chart. Below is the classification of events based on the objects:
- Application Events: These are events that are associated with the Excel application itself.
- Workbook Events: These are events that are associated with the actions that happen in a workbook.
- Worksheet Events: These events are associated with the action that happens in a worksheet.
- Chart Events: These events are associated with the chart sheets (which are different from worksheets).
- Userform Events: These events are associated with the action that happens with a user form.
- OnTime Events: OnTime events are those which can trigger code at a particular point in time.
- OnKey Events: OnKey events are those which can trigger code when a particular key is pressed.
6. Range
The range object is the most common and popular way to refer to a range in your VBA codes. You need to refer to the cell address, let me tell you the syntax.
Worksheets(“Sheet1”).Range(“A1”)
7. Conditions
Just like any other programming language, you can also write codes to test conditions in VBA. It allows you to do it in two different ways.
- IF THEN ELSE: It’s an IF statement that you can use to test a condition and then run a line of code if that condition is TRUE. You can also write nesting conditions with it
- SELECT CASE: In the select case, you can specify a condition and then different cases for outcomes to test to run different lines of code to run. It’s a little more structured than the IF statement.
8. VBA Loops
You can write codes that can repeat and re-repeat an action in VBA, and there are multiple ways that you can use to write code like this.
- For Next: The best fit for using For Next is when you want to repeat a set of actions a fixed number of times.
- For Each Next: It’s perfect to use when you want to loop through a group of objects from a collection of objects.
- Do While Loop: The simple idea behind the Do While Loop is to perform an activity while a condition is true.
- Do Until Loop: In the Do Until, VBA runs a loop and continues to run it if the condition is FALSE.
9. Input Box and Message Box
- Input Box: The input Box is a function that shows an input box to the user and collects a response.
- Message Box: Message Box helps you show a message to the user but, you have an option to add buttons to the message box to get the response of the user.
10. Errors
Excel has no luck when it comes to programming errors, and you have to deal with them, no matter what.
- Syntax Errors: It’s like typos that you do while writing codes, but VBA can help you by pointing out these errors.
- Compile Errors: It comes when you write code to perform an activity, but that activity is not valid.
- Runtime Errors: A RUNTIME error occurs at the time of executing the code. It stops the code and shows you the error dialog box.
- Logical Error: It’s not an error but a mistake while writing code and sometimes can give you nuts while finding and correcting them.
Write a Macro (VBA Program) in Excel
I have a strong belief that in the initial time when someone is starting programming in Excel, HE/SHE should write more and more codes from scratch. The more codes you write from scratch, the more you understand how VBA works.
But you need to start with writing simple codes instead of jumping into complex ones. That’s WHY I don’t want you to think about anything complex right now.
You can even write a macro code to create a pivot table, but right now, I don’t want you to think that far. Let’s think about an activity that you want to perform in your worksheet, and you can write code for it.
- Go to the Developer Tab and open the Visual Basic Editor from the “Visual Basic” button.
- After that, insert a new module from the “Project Window” (Right-click ➢ Insert ➢ Module).
- After that, come to the code window and create a macro with the name “Enter Done” (we are creating a SUB procedure), just like I have below.
- From here, you need to write a code which we have just discussed above. Hold for second and think like this: You need to specify the cell where you want to insert the value and then the value which you wish to enter.
- Enter the cell reference, and for this, you need to use RANGE object and specify the cell address in it, like below:
- After that, enter a dot, and the moment you add a dot, you’ll have a list of properties that you can define and activities that you can do with the range.
- From here, you need to select the “Value” property and set the text which you want to insert in the cell “A1” and when to do it, your code with look something like below.
- Finally, above the line of code, enter the text (‘this code enters the value “Done” in the cell A5). It’s a VBA Comment that you can insert to define the line of code that you have written.
Sub Enter_Done()
'this code enters the value “Done” in the cell A5
Range("A1").Value = "Done"
End Sub
Let’s understand this…
You can split this code into two different parts.
- In the FIRST part, we have specified the cell address by using the RANGE object. And, to refer to a cell using a range object you need to wrap the cell address with double quotes (you can also use square brackets).
- In the SECOND part, we have specified the value to enter into the cell. What you have done is, you have defined the value property for cell A5 by using “.Value”. After that, the next thing that you have specified is the value against the value property. Whenever you are defining a value (if it’s text), you need to wrap that value inside double quotation marks.
Here I have listed some of the most amazing tutorials (not in any particular sequence) that can help you learn VBA in NO TIME.
Visual Basic for Applications in the context of Excel
What is VBA?
VBA is an abbreviation for Visual Basic for Application. VBA is a programming language that was developed by Microsoft Corp., and it is integrated into the major Microsoft Office applications, such as Word, Excel, and Access.
The VBA programming language allows users to access functions beyond what is available in the MS Office applications. Users can also use VBA to customize applications to meet the specific needs of their business, such as creating user-defined functions, automating computer processes, and accessing Windows APIs.
Key Highlights
- Learning VBA programming can help Microsoft Office users access functions beyond what is directly available in the various Office applications.
- VBA can be used to analyze large amounts of data, create and maintain complicated financial models.
- Recording a macro is relatively simple and requires no inherent knowledge of the VBA code and will work for simple processes. However, this method is not very customizable.
How is VBA used?
VBA is used to perform different functions, and different types of users use the programming language for various functions. The following are the different parties that use VBA:
1. General users
Most users regularly use MS Office applications such as Excel in their routine. VBA language is included in the MS Office package at no cost to the user. VBA is used to automate tasks and perform several other functions beyond creating and organizing spreadsheets.
For example, users need to automate some aspects of Excel, such as repetitive tasks, frequent tasks, generating reports, etc. The user can create a VBA program (macro) within Excel that generates, formats, and prints monthly sales reports with graphical representation such as bar charts. They can execute the program with a single click, and Excel will automatically generate the reports with ease as per the needs of the company.
2. Computer professionals
Computer professionals can use VBAs to perform more complex tasks that would otherwise take longer time and more resources to complete. For example, they can use VBAs to create custom add-ins for Excel that provide additional functionality to the application by introducing new functions that are not available in Excel.
VBA also helps computer professionals perform complex functions, such as replicating large lines of code, designing languages within MS Office applications, and merging the functions of two or more different programs.
3. Corporate users
VBA is not only useful to individuals, but also to corporate users. Companies can use the VBA programming language to automate key business procedures and internal processes. Functions such as accounting procedures, tracking minutes, processing of sales orders in real-time, calculating complex data, etc., can be implemented using VBA.
VBA can automate the above-mentioned tasks to increase the efficiency of internal business processes. It also allows corporations to consolidate their data in the cloud to make it accessible from any location around the world.
Common uses of VBA among finance professionals
The following are some of the ways in which finance professionals use VBA in their work:
1. Analyze huge amounts of data
Finance professionals, such as portfolio managers, financial analysts, traders, and investment bankers, often need to deal with large volumes of data. They are required to review all the data and use the information to make critical buy or sell decisions. The professionals can use VBA to create macros that facilitate speedy analysis of the data.
Once the logic is defined and the important variables are specified, the finance professionals should feed the large volumes of data into the relevant cells and get results with a click of a button. Also, as long the correct data is added to the program, the data output will be more accurate compared to the output obtained manually since humans are bound to make mistakes.
2. Create and maintain complex models
Finance professionals can also use VBA to create trading, pricing, and risk management models. The models can be used to track the performance of stocks in the securities exchange market in real-time, forecast the trend of each stock, and provide signals on when to buy or sell and the appropriate pricing at each stage.
The VBA program can also be used to generate financial ratios that allow analysts to evaluate the financial performance of publicly traded companies, as well as compare the trends and performance of two or more entities over a defined period of time.
3. Create investment scenarios
Investment bankers and financial analysts often need to make decisions by comparing two or more investment scenarios. For example, in mergers and acquisitions, finance professionals must consider the financial impact of the merger to determine if it is feasible. The professionals can use VBA to create macros that simulate the investment scenarios to get an overview of the expected results/effects.
In such a way, it can eliminate human emotions that may interfere with the decision-making process and instead rely on a simulated analysis that is theoretically closer to reality. The decision-makers can make a decision based on the obtained results.
Why use Excel VBA?
While users cannot directly manipulate the main Excel software through VBA, they can master the art of making macros to optimize their time in Excel. There are two ways to make Excel macros.
The first method is to use the Macro Recorder. After activating the recorder, Excel will record all the steps a user makes and save it as a “process” known as a macro. When the user ends the recorder, this macro is saved and can be assigned to a button that will run the exact same process again when clicked. This method is relatively simple and requires no inherent knowledge of the VBA code. This method will work for simple processes.
However, the downfall of this method is that it is not very customizable, and the macro will mimic the user’s input exactly. By default, recorder macros also use absolute referencing instead of relative referencing. It means that macros made in this way are very hard to use with variables and “smart” processes.
The second and more powerful method of creating an Excel macro is to code one using VBA.
Where to code Excel VBA
To access the VBA window, press Alt + F11 within any Office program. When done properly, this will open a window with a file structure tree on the top left, properties on the bottom left, a debug pane at the bottom center and bottom right, and the coding section that takes up the majority of the screen in the center and top right. This may seem overwhelming at first, but in reality, it’s simpler than it appears.
Most of the time, the user will be working in the coding section. The file structure section is only used for creating a new macro file. The properties section in the bottom left will only be used for more advanced macros that use UserForms to create graphical interfaces for the macro.
The coding section is where most, if not all, of the coding happens. The user will create, code, and save macros here. After the macro code is written and saved, it can then be attached to certain triggers in the Excel model. The macro can be activated at the push of a specific button on the worksheet, or when certain cells are modified, for example. The easiest way to implement a macro is to attach it to a button.
VBA shortcuts in Excel
The following are some of the shortcuts that work when using VBA in MS Excel:
- Alt + F11: Open VBA Editor
- Alt + F8: Display all macros
- Alt + F4: Close VBA Editor and return to Excel
- F7: Open code editor
- F1: Display Help
- Ctrl + Space: Autocomplete
- F10: Activate menu bar
- Home: Beginning of line
- Alt + F5: Run Error Handler
- Alt + F6: Switch between the last two windows
- Alt + F11: Toggle between VBA Editor and Excel
Related articles
Excel Functions List
Financial Modeling Macros
Transitioning from Excel to Python
Financial Modeling Using VBA
Excel VBA for Finance
See all Excel resources
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
If you’ve ever used macros in Excel, you’ve used Visual Basic for Applications (VBA). VBA is human-readable (and editable) programming code that gets generated when you record a macro. When you run a macro it’s this code that Excel reads to replay your actions.
The following is a series of frequently asked questions about VBA, with answers for both newcomers to Excel macros and seasoned programmers.
What is VBA used for in Excel?
VBA is used to write macros, which automate simple and complex tasks in Excel.
Users of Microsoft Excel will often find themselves repeating the same series of tasks over and over again. Sometimes these are minor tasks like copy-pasting subsets of data to different sheets, and sometimes the tasks are more complex like uploading data to a website. With VBA, macros can be programmed to automate tasks like these, turning a series of manual operations into a single button click.
How do I start with VBA in Excel?
The easiest way to get started with macros is to record them using the Macro Recorder built into Excel. The macro recorder generates VBA code which you can read and edit, giving you a stepping-stone to learn how to code your own macros from scratch.
For more information, see the article “How to Record a Macro”.
How can I access VBA code?
The VBA editor can be opened at any time by pressing the ALT+F11 keyboard shortcut. From here, you can access the code for all open workbooks.
You can double-click any workbook, sheet, or module object in the Project window to show the VBA code contained in it. Recorded macros will always appear in modules, which is where you’ll typically want to write your own macros too.
For more information about editing macros, see the article “Editing Excel VBA Macros“.
What can VBA do?
First of all: if there’s something you can do in Excel, you can write VBA code to do the same thing. If you learn the commands (using the macro recorder or online resources), you can string together several actions together in a single macro.
Second: you can use VBA to write user-defined functions for use in worksheet formulas – much like the “=SUM()” function, for example. Although Excel already packs a large variety of functions, if you find yourself wanting a function that’s more specific to your industry or workplace, you can add it with VBA.
Third: you can use VBA to add logic (If statements) and loops (repeat actions) to your macros. This means that a macro can be more than a recording of actions – it can be a real program with smart repetition and decision-making.
Fourth: VBA allows you to build user interfaces, giving users an easier way to interact with your macros. These interfaces can be simple buttons on a worksheet, or complex UserForms with rich controls like TreeViews and FlexGrids.
(See the article “Add a Button and Assign a Macro in Excel” as a starting point.)
Fifth but not finally: VBA allows you to harness almost any resource your computer or the internet by using external DLL libraries. You can automate a lot more than Excel this way, like accessing web services and databases, parsing XML files, interoperating with other Microsoft Office applications, and much, much more.
Are VB and VBA the same?
The VBA language is identical to Visual Basic 6.0. If you have experience writing VB6 code, you can write VBA.
The VB Editor in Excel is a stripped-down version of the VB6 editor, with similar debugging capabilities and components like the ‘Project’ and ‘Properties’ windows. The Form editor is also very similar, although it has some limitations (like the inability to create control arrays).
Less similar to VBA is Visual Basic .NET. Although these languages share many of the same keywords and syntaxes, the code between these languages is less interoperable. You wouldn’t have to re-write much (if anything) to port a procedure from VB6 to VBA, but you couldn’t do the same from VB.NET.
What is the difference between a macro and VBA?
VBA is just the language that macros are written with. If your macro is a story, VBA is the grammar and dictionary it’s written with.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
What is the difference between a macro and a script?
Scripts use a limited subset of the Visual Basic language and are used for different purposes.
Macros are stored inside Excel workbook files and can only be run from inside Excel. They’re typically used to automate various Excel functions and add extra functionality to workbooks.
Scripts are stored in text files using the .VBS extension and can be run from inside Windows or executed by other programs. Sysadmins will use scripts to automate certain administrative tasks on a computer or network.
What does a VBA Developer do?
Often, people who create macros aren’t developers – they’re analysts, traders, accountants, or scientists, who have had training in programming and use VBA on more of an ad-hoc basis.
People who focus on VBA development tend to create more refined tools – they create Add-ins, user interfaces with Forms, interactive dashboards, report generators, and more.
Why is VBA important?
VBA is included as standard in all Microsoft Office applications, including Excel. Excel is one of the most popular programs in the world and finds use in a wide variety of fields and workplaces, all with their own unique workflows and use-cases.
By not using automation, countless work-hours are wasted every week performing boring, repetitive tasks at a human speed. Automation with VBA can perform the same tasks at the computer’s lightning-quick pace, letting users focus on the important aspects of their work, being more productive – and maybe getting out of the office a little earlier!
VBA Programming | Code Generator does work for you!
Is VBA a good programming language?
VBA has the typical programming elements like variables, arrays, functions, decisions and loops. It has a syntax that’s easy to read, and can harness a lot of power from Windows and other services.
On the downside, error-handling isn’t very elegant in VBA. While other languages use “try-catch-finally” code blocks, VBA uses “On Error” statements to modify how macros behave when an error occurs.
Additionally, VBA can’t be used to create standalone programs, web sites or services, and it can’t interface with newer programming APIs like the .NET platform.
Is VBA object-oriented?
VBA has some limited support for some object-oriented concepts:
- Encapsulation: VBA supports data hiding using classes
- Polymorphism: the Implements keyword allows programmers to use other classes as interfaces
In the strict sense though, VBA is not object-oriented. It notably lacks the concept of inheritance, which severely limits the ability to extend the functionality of existing types.
Visual Basic for Applications (VBA) in Excel, is a powerful and sophisticated built-in programming language that allows you to write your own functions or commands in an Excel spreadsheet.
These custom functions or commands, can help to ease your tasks and thus by using Excel VBA you can do almost any imaginable thing in Excel.
Now, before we dive deep into Excel VBA, let’s first try to understand what VBA is.
What is VBA?
In most simple terms you can also say that, VBA is the language that Office Applications like Excel, Word, PowerPoint, etc. understand. So, all the programming that we are going to do in Excel or in other office application has to be done in VBA.
But technically, VBA is an implementation of Microsoft’s event-driven programming language i.e. VB6 and its associated integrated development environment (IDE).
VBA is an extensible programming language that is made up of a core set of commands and extended on a per-application basis to be able to work directly with objects in that application. And because of this it is sometimes also called as a hosted language.
Visual Basic for Applications is bundled with office applications (host application) so that it can be used as medium for accessing and interacting with the host applications object model. This means that, Excel VBA, knows about things like workbooks, worksheets, cells and charts, but Word VBA doesn’t knows about such things. Instead Word VBA understand terms like documents, bookmarks etc., things that are more related to Microsoft Word.
Is there any difference between a VBA Program and Macro?
I have seen many people confusing between VBA and Macro language. But a Macro language is very much different from a VBA. Macros were used with the older versions of office applications and they could only be used for automating instructions.
In fact, the first spreadsheet macro programs were just shortcuts for the user interface commands. For example, if in the user interface you typed R (for “Range”), N (for “Name”), and C (for “Create”), you would enter RNC into the macro to automate the process.
This approach was intuitive, but it also had integral weaknesses. Because of such weaknesses, VBA later in 1993 replaced this Macro Language, and hence there is still a misconception among people to call VBA as macro language.
Visual Basic for Applications when compared to traditional Macro Language is more powerful and sophisticated and hence it was an instant success.
Why learning Excel VBA is so important?
As you become familiar with Excel, you will notice that although Excel provides you large number of tools, but still it doesn’t have everything that you need to perform your daily tasks. Such tasks may include creating custom functions, repetitive instructions, automating tasks etc.
And hence Microsoft has provided VBA as a gap filler; that allows users to write their own methods or commands to perform their tasks.
After having enough experience with VBA programming in Excel you will never ever get stuck during your tasks due to a lack of built-in tools. Using Visual Basic for Applications you will be able to write your own function and commands whenever you feel the need to write one.
What all you can do with Excel VBA?
With Excel VBA you can do a lot of things in Excel. I have enlisted few of them below:
- You can automate the tasks that you have to do frequently.
- You can create a custom command in excel.
- You can repeat a set of instructions multiple times.
- You can create custom function popularly called as User Defined Function (UDF)
- You can create a custom add in in Excel.