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
What is Programming in Excel?
Programming refers to writing a set of instructions that tell Excel to perform one or more tasks. These instructions are written in the Visual Basic for Applications (VBA) as this is the language understandable to Excel. To write an instruction, one can either write a code in VBA or record a macro in Excel. A macro is recorded to automate repetitive tasks. When a macro is recorded, VBA generates a code in the background.
For example, to submit an Excel report, a table needs to undergo the same set of tasks each time. These tasks include applying a pre-defined border, color, alignment, and font. To program in Excel, a macro can be recorded for performing all these tasks.
The purpose of programming in Excel is to save the user from performing the same tasks again and again. Moreover, it helps accomplish multiple tasks at a great speed that would have taken a lot of time, had they been performed manually.
Table of contents
- What is Programming in Excel?
- Stages of Programming in Excel VBA
- Stage 1–Enable the Developer Tab in Excel
- Stage 2–Record a Macro in Excel
- Stage 3–View and Examine the VBA Code Generated by the Recorded Macro
- Stage 4–Test the VBA Code of the Recorded Macro
- Stage 5–Save the Recorded Macro (or the VBA Code)
- Frequently Asked Questions
- Recommended Articles
- Stages of Programming in Excel VBA
Stages of Programming in Excel VBA
Programming in Excel VBA is carried out in the following stages:
- Enable the Developer tab in Excel
- Record a macro in Excel
- View and examine the VBA code generated by the recorded macro
- Test the VBA code of the recorded macro
- Save the recorded macro (or the VBA code)
Further in this article, every stage of programming ine xcel has been discussed one by one. The steps to be performed in each stage are also listed.
Stage 1–Enable the Developer Tab in Excel
Let us understand how to enable the Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more in Excel. This tab is enabled to record a macro and access VBA. When the Developer tab is enabled, it appears on the Excel ribbonRibbons in Excel 2016 are designed to help you easily locate the command you want to use. Ribbons are organized into logical groups called Tabs, each of which has its own set of functions.read more. However, by default, Excel does not display the Developer tab.
Note: To know an alternate method to record a macro and access VBA, refer to the “alternative to step 1” in stages 2 and 3.
The steps to enable the Developer tab in Excel are listed as follows:
Step 1: Go to the File tab displayed on the Excel ribbon.
Step 2: Select “options” shown in the following image.
Step 3: The “Excel options” window opens, as shown in the following image. Select “customize ribbon” displayed on the left side of this window.
Step 4: Under “choose commands from” (on the left side of the window), ensure that “popular commands” is selected. Under “customize the ribbon” (on the right side of the window), choose “main tabs” from the drop-down list.
Next, select the checkbox of “developer” and click “Ok.” This checkbox is shown in the following image.
Step 5: The Developer tab appears on the Excel ribbon, as shown in the following image.
Stage 2–Record a Macro in Excel
Let us learn how to record a macroRecording macros is a method whereby excel stores the tasks performed by the user. Every time a macro is run, these exact actions are performed automatically. Macros are created in either the View tab (under the “macros” drop-down) or the Developer tab of Excel.
read more in Excel. When a macro is recorded, all tasks performed by the user (within the workbook) are stored in the Macro Recorder until the “stop recording” option is clicked. Apart from Microsoft Excel, a macro can be recorded for all Office applications that support VBA.
The steps to record a macro in Excel are listed as follows:
Step 1: From the Developer tab, click “record macro” from the “code” group.
Alternative to step 1: One can also click “record macro” from the “macros” group of the View tab of Excel.
Step 2: The “record macro” window opens, as shown in the following image. In this window, one can name the macro before recording it. The default macro name given by Excel is “macro1.”
The rules governing a macro name are stated as follows:
- It should not contain any space ( ), period (.) or exclamation point (!).
- It cannot contain any special characters (like $, @, ^, #, *, &) except the underscore (_).
- It should not begin with a numerical value. Rather, it must start with a letter.
- It cannot exceed 255 characters in length.
Note: It is recommended to use short and meaningful names for macros. Further, one must assign a unique name to each macro. In VBA, two macros within the same code module cannot have the same names.
Step 3: In the “macro name” box, we have entered the name “recording_macro.”
Notice that an underscore has been used as a separator between the two strings (recording and macro) of the name. No spaces, periods or special characters have been used in this name.
Step 4: Click “Ok” to start recording the macro. Once “Ok” is clicked in the preceding window, the “record macro” button (in the Developer tab or the View tab) changes to the “stop recording” button.
Next, carry out the tasks to be recorded in the macro “recording_macro.”
Note: Since the Macro Recorder records every action performed by the user, ensure that the actions are executed in the right sequence. If the recorded sequence is correct, Excel will perform the tasks efficiently each time the macro is run.
However, if a sequencing error occurs, one must either re-record the actions or edit the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more manually. If one is recording the macro for the first time, it is recommended to keep a copy of the workbook to prevent any undesired changes to the stored data.
In the following steps (step 4a to step 4c), the tasks to be recorded have been performed.
Step 4a: Select cell A1 of the worksheet. This is the first task that is recorded. The selection is shown in the following image.
Step 4b: Type “welcome to VBA” in cell A1. This is the second task that is recorded. Exclude the beginning and ending double quotation marks while typing.
Step 4c: Press the “Enter” key. As a result, the selection shifts from cell A1 to cell A2. This becomes the third task that is recorded.
The selection is shown in the following image.
Step 5: Click “stop recording” in the “code” group of the Developer tab. By clicking this option, Excel is told to refrain from recording any further tasks.
The “stop recording” option is shown in the following image.
Stage 3–View and Examine the VBA Code Generated by the Recorded Macro
Let us observe and study the VBA code generated by the macro recorded in stage 2. Remember that one can either directly write a code in the Visual Basic Editor (VBE or VB Editor) or let a macro do the same.
The VBE is a tool or program where VBA codes are written, edited, and maintained. When a macro is recorded, a code is automatically written in a new module of VBE. Note that VBA is the programming language of Excel.
The steps to view and study the code generated by the recorded macro are listed as follows:
Step 1: Click “visual basic” from the “code” group of the Developer tab. This option is shown in the following image.
Alternative to step 1: As a substitute for the preceding step, press the keys “Alt+F11” together. This is the shortcutAn Excel shortcut is a technique of performing a manual task in a quicker way.read more to open the VBE window.
Note: “Alt+F11” is a toggle key which when pressed repeatedly, helps to switch between VBE and Excel.
Step 2: The Visual Basic Editor window opens, as shown in the following image.
To the left of the VBE window, the worksheet, workbook, and module are shown. This window on the left (named “Project-VBAProject”) is also known as the Project window or the Project Explorer of VBE.
Step 3: Double-click “modules” shown in the following image.
Note: “Modules” are folders shown in the Project window after recording a macro. They are not shown prior to recording a macro. “Modules” are also shown when a module is inserted manually from the Insert tab of the VBE.
Step 4: Double-click “module1” under modules. A code appears on the right side of the VBE window. This window on the right [named “Book1-Module1 (Code)”] is known as the module code window.
The code is displayed in the following image.
Note: The code generated by recording a macro can be checked in the “modules” folder (in the module code window). In a module code window, one can also write a code manually or copy-paste it from another source.
In the following steps (step 4a to step 4d), the code generated by the recorded macro has been studied.
Step 4a: The first word of the code is “Sub.” “Sub” stands for subroutine or procedure. At the start of the code, the word “Sub,” the macro name (recording_macro), and a pair of empty parentheses are displayed. This is followed by the statements to be executed by the code. These statements are:
ActiveCell.FormulaR1C1 = “Welcome to VBA”
Range (“A2”). Select
The code ends with “End Sub.”
The start or head [Sub Recording_Macro ()] and the end or tail [End Sub] of the code are shown in the following image.
Note 1: The words “macro” and “code” are often used interchangeably by several Excel users. However, some users also distinguish between these two words.
A VBA code is a command created either by writing a code directly in VBE or by recording a macro in Excel. In contrast, a macro consists of instructions that automate tasks in Excel. According to one’s choice, one can decide whether or not to differentiate between the two words.
Note 2: The “Sub” can be preceded by the words “Private,” “Public,” “Friend,” or “Static.” All these words set the scope of the subroutine. The default subroutine used in VBA is “Public Sub.” So, when “Sub” is written in a code, it implies “Public Sub.”
A “Public Sub” can be initiated by subroutines of different modules. However, a “Private Sub” cannot be initiated by subroutines of other modules.
Step 4b: The first activity we performed (in step 4a of stage 2) was to select cell A1. Accordingly, the following statement of the code tells Excel that the active cell is R1C1.
ActiveCell.FormulaR1C1
When a macro is recorded, VBA uses the R1C1 style for referring to cells. In this style, the letter R is followed by the row number and the letter C is followed by the column number. So, cell R1C1 implies that the row number is 1 and the column number is also 1. In other words, cell R1C1 is the same as cell A1 of Excel.
Step 4c: The second activity we performed (in step 4b of stage 2) was to type “welcome to VBA” in cell A1. So, the following statement of the code tells Excel that the value in cell R1C1 is “welcome to VBA.”
ActiveCell.FormulaR1C1 = “Welcome to VBA”
Step 4d: The third activity we performed (in step 4c of stage 2) was to press the “Enter” key. By pressing this key, the selection had shifted from cell A1 to cell A2. Therefore, the following statement tells Excel to select cell A2.
Range (“A2”). Select
This is the way VBA generates a code for all the activities performed under stage 2 of programming in Excel. Examining the code line-by-line makes it easier to interpret it.
Stage 4–Test the VBA Code of the Recorded Macro
Let us test the code when it is run multiple times. Note that a macro (or code) can be run as many times as one wants. Each time it runs, it performs the recorded tasks in Excel.
The steps to test the code that we examined in stage 3 are listed as follows:
Step 1: Delete the string “welcome to VBA” from cell A1 of Excel. Let A1 remain as a blank, selected cell. The following image shows the empty cell A1.
Note: To go back from VBE to Excel, press the toggle key “Alt+F11.”
Step 2: Go to VBE again by pressing the key “Alt+F11.” Click anywhere within the code. Next, click the “Run Sub/UserForm (F5)” button. This button is shown within a blue box in the following image.
Note: Alternatively, one can press the key F5 to run the VBA code.
Step 3: The output is shown in the following image. The preceding code enters the string “welcome to VBA” in cell A1. Thereafter, the selection shifts to cell A2. The string “welcome to VBA” has been entered in cell A1 because this cell was selected (in step 1) before running the code.
Each time the code is run, the currently selected cell (or the active cell) is filled with the string “welcome to VBA.” Then, the selection shifts to cell A2. So, if cell M10 is the active cell, running the code fills this cell with the stated string and selects cell A2 at the end.
However, had cell A2 been selected, running the code would have filled this cell with the string “welcome to VBA.” Moreover, in the end, cell A2 would have remained the selected cell.
Stage 5–Save the Recorded Macro (or the VBA Code)
Let us learn how to save a workbook containing a recorded macro. If a macro is saved, its VBA code is also saved.
The steps to save a workbook containing a macro (or a VBA code) are listed as follows:
- Click “save as” from the File tab of Excel. The “save as” dialog box opens, as shown in the following image.
- Assign a name to the Excel workbook in the “file name” box. We have entered the name “macro class.”
- Save the workbook with the “.xlsm” extension. So, in the “save as type” box, choose “Excel macro-enabled workbook.”
- Click “save” to save the workbook.
A workbook containing a macro should always be saved with the “.xlsm” extension. This extension ensures that the macro is saved and can be reused the next time the workbook is opened.
Note 1: The “save as” command is used when a workbook is saved for the first time. It is also used when a new copy of the workbook is to be created and, at the same time, the original copy is to be retained as well.
Note 2: If the workbook containing a macro is saved as a regular workbook (with the “.xlsx” extension), the macro will not be saved. Further, one may lose the code of the recorded macro.
Frequently Asked Questions
1. What is programming and how is it carried out in Excel?
Programming refers to instructing Excel to perform one or more tasks. To instruct Excel, either a code can be written in the Visual Basic for Applications (VBA) or a macro can be recorded in Excel. Each time a macro is recorded, a code is generated by VBA in the background.
The steps to carry out programming in Excel are listed as follows:
a. Enable the Developer tab in Excel.
b. Record a macro in Excel. For recording, perform each activity in the sequence in which it should be recorded.
c. Save the code generated by the recorded macro and run it whenever required.
One can also carry out programming by writing a code manually and then saving and running it.
Note: To learn the details of programming in Excel, refer to the description of the different stages given in this article.
2. How to write a code for programming in Excel?
For programming in Excel, a code is written in Visual Basic Editor (VBE), which is a tool of VBA. The steps to write a code in VBE are listed as follows:
a. Open a blank Excel workbook.
b. Press the keys “Alt+F11” to open VBE.
c. Select any worksheet from “Microsoft Excel Objects” listed in the “Project-VBA Project window.”
d. Click the Insert tab and choose “module.” A folder named “modules” and an object named “module1” are created in the “Project-VBA Project window.” At the same time, a window opens on the right, which is titled “Book1-Module1 (Code).”
e. Enter the code in the “Book1-Module1 (Code)” window that has opened in the preceding step.
f. Click anywhere within the code once it has been written entirely.
g. Run the code by pressing F5 or clicking the “Run Sub/UserForm (F5)” button.
If the code has been entered correctly in step “e,” Excel will perform the tasks it has been instructed to. However, if there is an error in the code, an error message will appear.
Note: For saving a code, refer to stage 5 of programming in Excel given in this article.
3. How to learn programming in Excel?
To learn programming, one can learn how to record a macro in Excel. It is easier to learn macro recording than to create a code manually in VBE. Moreover, macro recording can be done even if one does not know VBA coding.
However, each time a macro is recorded, examine the generated code carefully. As one becomes proficient in macro recording, the codes too will become understandable. In this way, learning programming in Excel will no longer be a complicated task.
Recommended Articles
This has been a guide to Programming in Excel. Here we discuss how to record VBA macros along with practical examples and downloadable Excel templates. You can learn more from the following articles–
- Create Button Macro in ExcelA Macro is nothing but a line of code to instruct the excel to do a specific task. Once the code is assigned to a button control through VBE you can execute the same task any time in the workbook. By just clicking on the button we can execute hundreds of line, it also automates the complicated Report.read more
- What is VBA Macros?
- Excel MacroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
read more - Code in Excel VBAVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more
How to Use the VBA Editor in Excel: Quick Guide (2023)
Excel’s Visual Basic for Applications (VBA) editor is a very powerful tool.
It lets you write and edit custom scripts that automate actions in Excel.
In fact, when you record a macro it is stored in VBA code in the VBA editor.
But writing a macro from the VBA editor directly gives you more flexibility than recording a macro in the traditional manner.
You can create better VBA code and complete more complicated tasks by working directly with Visual Basic for Applications.
In this tutorial, I show you the basics of how to use Excel’s VBA editor. Let’s get into it!
What is the VBA editor?
The Visual Basic editor, also called the VBA editor, VB editor, or VBE, is an interface for creating scripts.
VBA (Visual Basic for Applications) is the coding language that’s used to create these scripts.
Visual Basic is a full-featured programming language, but Microsoft Office’s very own VBA programming language is easier to get the hang of, so you can get started with developing applications much more quicker.
If you’ve done any programming in an integrated development environment (IDE), the VBA editor in Excel will look familiar. It lets you create, manage, and run VBA code on your Excel spreadsheet.
Let’s take a look at how to open the Visual Basic editor and do a few basic things.
How to use the VBA editor in Excel
Before you start coding, you’ll need to open the VBA editor. To do this, head to the Developer tab and click the Visual Basic button:
If you don’t see the Developer tab, go to File > Options > Customize Ribbon and make sure that the developer tab is checked in the right pane. If you want a more thorough explanation of how to add the developer tab in Excel, read it here.
You can also open the VBA editor with the shortcut key Alt + F11.
As you can see, the VBA editor is packed full of buttons, menu bars, and options. Don’t worry—we’ll go through the important ones in this guide.
In this guide, we’ll focus on the most basic parts of the Visual Basic editor.
The project view, in the left, vertical, menu bar in the VBA editor, has a folder called Modules.
This folder holds Excel VBA modules, which are like containers for VBA code. When you record macros, they’re included in a module.
Modules also contain the code window where you’ll be writing code (if you’re not recording it).
To add a new, empty module, click the Insert menu button and select Module.
If there was no Modules folder in VBAProject, the folder will be created and there will be a new module inside of it. This is where you’ll put your Excel VBA code when you’re ready to write it.
To delete a module, right-click it in the left pane and select Remove [module name].
Excel will ask you to confirm the removal. You may export the module if you’d like to save it.
Finally, let’s look at running a macro from the Visual Basic Editor window.
After you’ve created a macro, either by coding it directly or recording it from the standard Excel interface, you can run it from this view.
To run a macro, just click the Run Macro button in the menu bar:
You can also press the shortcut key F5 on your keyboard to run the macro from the VBA editor.
PRO TIP: Change the name of a module
If you’re developing big spreadsheets with lots of VBA, all the macro codes won’t be able to fit in one single module. You’ll need more. You can easily add those from the menu bar, but as you add more, it becomes increasingly more difficult to figure out what macros are in what modules.
Luckily, you can easily change the name of a module in the Properties window.
Add the Properties code window from the Insert button on the menu bar.
If the Project window is missing
If it looks like this when you open the Visual Basic editor:
The code window is missing, there’s no left vertical menu bar. Nothing is visible except the horizontal menu bar on top 🤷
You need to click on the ‘View’ tab on the menu bar, and then click to show the ‘Project Explorer’ window.
That’s it – Now what?
This was a simple Excel tutorial on getting started with the Visual Basic editor in Excel and should get you on the right track to write code (or record it).
Mastering the Excel VBA editor is important for both beginners and advanced Excel users.
When you write more VBA code, you’ll see that the Excel VBA editor becomes a better help for you in your work.
For instance, it helps you autocomplete your VBA coding with IntelliSense, helps you find syntax errors with auto syntax check, debug with the immediate window, uses the object code window, and much more.
For now, play around with the VBA editor to get a feel for where the buttons and menus are, and start getting used to the structure of VBA.
If you want to dive deeper into VBA programming, check out my free 30-minute VBA course here.
Other resources
The VBA editor is just a tiny portion of what macros are all about. You definitely need to check out my big VBA guide here.
Frequently asked questions
To open the Visual Basic Editor in Excel, follow these steps:
- Click the Developer tab.
- Click the Visual Basic button in the Code group on the Developer tab. This opens the VBA editor.
- Alternatively, you can open the VBA editor by pressing the Alt + F11 shortcut keys.
There is no need to install the VBA editor. It should already be available in your Excel program.
But you might be missing the developer tab. To add it:
- Click the File tab and Options.
- Then click the Customize Ribbon tab.
- Under Customize the Ribbon, in the right pane, select the Developer check box.
- Click OK.
Kasper Langmann2023-01-30T19:50:45+00:00
Page load link
Excel VBA Code Programming
VBA code can be defined as the code that inputs in the visual basic window to perform a set of instructions or actions in excel and provide results. With the help of VBA code, we can reduce the time to perform a repetitive task, there will not be required much human intervention except to run the program. Now we will see how to open a visual basic window, how to write code in it, how to run, and how to save it.
How to Open a Visual Basic Window?
If you want to write the visual basic code, we should write it in a visual basic window. The question here is, where is the visual basic window in excel and how to open it. The answer is to select the Developer menu and under the developer menu, choose Visual Basic as shown in the below image.
Which will open the blank window as shown below.
Easy and looks cool right. But incase if excel does not have Developer tab. We need to add the developer tab with the below steps.
Step 1: Click on File Option.
Step 2: Drop-down appears, click on Options tab.
Step 3: Once you click on “Options”, a dialog box appears as shown below and click on the Customize Ribbon option.
Step 4: When we drag down in the customize ribbon options we will find an option for Developer (Custom) we need to check that box which will enable us to use VBA in excel.
Another easy way to open the Visual basic window is by pressing Alt+F11
Where to Write Code in Excel VBA?
By default, there will be two modules available to write your code, one is sheet1 module and workbook module.
If we add multiple sheets in our workbook it will allow different sheet modules here.
Sheet Module Code: Whatever the event code we write in the sheet module it will apply for that sheet alone.
You may be in confusion what is an event code. VBA comes with multiple events shown in the above screenshot, events like change, deactivate and many more. Whenever that event happened the macro will run.
ThisWorkbook Module
Whatever the code written in this module will apply for all the sheets in the workbook. Suppose if we write an event code for the workbook then whenever that event happened in any of the sheets of the workbook the macro will run. Suppose if we write an event for “New sheet” then whenever we created a new sheet the macro will run for that workbook.
Module: Normally we will write code in modules in VBA. We need to insert the module by clicking on the Insert menu and select the module option to insert a module.
Similarly, we can insert a class module and user form also. These are the modules where we can write our code. Depend on the type of requirement we should choose the module and write the code in it.
Examples to Write and Run Code in Excel VBA
Below are the different examples to write and run the code using VBA Code in Excel.
You can download this VBA Code Excel Template here – VBA Code Excel Template
Example #1 – Macro Code using a Normal Module
Now we will see a sample macro code using a normal module. When we insert a new module, the empty window will look like below.
Follow the below steps to write code in excel VBA.
Step 1: Any program in VBA starts with sub keyword and program name with open and close brackets as below. When we enter after the brackets automatically “End Sub” will appear.
Code:
Sub sample() End Sub
Step 2: In between, we should write our code.
Code:
Sub sample() Cells(1, 1).Value = "Name" Cells(1, 2).Value = "Age" Cells(1, 3).Value = "Address" End Sub
In the above macro, I wrote a sample code like when I run the macro first three cells should fill with Name, Age and Address. Cells(1,1).value represents the cell of row1 and column1 value.
Step 3: We can run the code by pressing F5 or click on the run button at the top which is marked in Black colored box.
Step 4: Once we click on run, a pop up will ask for a run as below. If multiple macros are available need to choose the correct macro and click on the run button.
Step 5: Go to excel and check whether the results are appearing or not as below.
Example #2 – Attaching a Macro to a Shape
If we want to run the macro from the worksheet itself with the help of a shape, we can do that. Follow the below steps to assign the macro to shapes.
Step 1: Go to Insert, and Select the shape as per your wish.
Step 2: After selecting the shape, draw this on your worksheet.
Step 3: Now, we can write a text like “click here” or “run Macro” in that shape. For adding the text just right click on a shape and select Edit Text
Step 4: Add the word as per your wish. I have added the word as “Run Macro”.
Step 5: Now, we need to assign the macro to that shape, for that select the shape and right click and choose “Assign Macro” option.
Step 6: A pop-up box will come asking for macro selection. Select the macro name and click on the Ok button.
Step 7: Now, if we click on the shape the macro will run and give the result as below.
How to Save the Macro Workbook?
We all know how to save a workbook. Saving macro workbook is also same but one small change will be there. We have two different ways to save our macro files.
- Macro enabled workbook
- Macro enabled template
When you are saving the workbook, we need to choose the file type from the list of file type options as below.
By default, we can use the “Excel macro-enabled workbook”. In case if you want to use as standard file as a starting point for other files then use “Excel macro-enabled template” format.
Things to Remember
- Add the developer tab in case if it is not available in the menu ribbon.
- If want to create a simple basic macro, try to use recording a macro as it does not need any coding not even need to go to the visual basic screen. Click on record macro option from the developer tab and give macro name to perform the required steps. It will record the steps you are performing, once it is over, stops recording and can run the macro now as to how we run the macro in the above steps.
- Choose the module type depending on the requirement, by default we can write in a normal module.
- Do not forget to save the file in the macro-enabled format then only the workbook will be a macro-enabled workbook.
Recommended Articles
This is a guide to VBA Code in Excel. Here we learn how to Copy, Insert & Run the VBA Code in Excel along with simple and practical examples. Below are some useful excel articles related to VBA –
- VBA UBound
- VBA Get Cell Value
- VBA END
- VBA RGB
Первое знакомство с редактором VBA Excel, создание процедур (подпрограмм) и написание простейшего кода, работающего с переменными и ячейками рабочего листа.
Начинаем программировать с нуля
Часть 1. Первая программа
[Часть 1] [Часть 2] [Часть 3] [Часть 4]
Эта статья предназначена для тех, кто желает научиться программировать в VBA Excel с нуля. Вы увидите, как это работает, и убедитесь, что не все так сложно, как кажется с первого взгляда. Свою первую программу вы напишите за 7 простых шагов.
- Создайте новую книгу Excel и сохраните ее как книгу с поддержкой макросов с расширением .xlsm. В старых версиях Excel по 2003 год – как обычную книгу с расширением .xls.
- Нажмите сочетание клавиш «Левая_клавиша_Alt+F11», которое откроет редактор VBA. С правой клавишей Alt такой фокус не пройдет. Также, в редактор VBA можно перейти по ссылке «Visual Basic» из панели инструментов «Разработчик» на ленте быстрого доступа. Если вкладки «Разработчик» на ленте нет, ее следует добавить в настройках параметров Excel.
В левой части редактора VBA расположен проводник проекта, в котором отображены все открытые книги Excel. Верхней строки, как на изображении, у вас скорее всего не будет, так как это – личная книга макросов. Справа расположен модуль, в который записываются процедуры (подпрограммы) с кодом VBA. На изображении открыт модуль листа, мы же далее создадим стандартный программный модуль.
- Нажмите кнопку «Module» во вкладке «Insert» главного меню. То же подменю откроется при нажатии на вторую кнопку после значка Excel на панели инструментов.
После нажатия кнопки «Module» вы увидите ссылку на него, появившуюся в проводнике слева.
Первая программа на VBA Excel
Добавляем на стандартный модуль шаблон процедуры – строки ее начала и завершения, между которыми мы и будем писать свою первую программу (процедуру, подпрограмму).
- Откройте стандартный модуль двойным кликом по его ссылке в проводнике. Поместите в него курсор и нажмите кнопку «Procedure…» во вкладке «Insert» главного меню. Та же ссылка будет доступна при нажатии на вторую кнопку после значка Excel на панели инструментов.
В результате откроется окно добавления шаблона процедуры (Sub).
- Наберите в поле «Name» имя процедуры: «Primer1», или скопируйте его отсюда и вставьте в поле «Name». Нажмите кнопку «OK», чтобы добавить в модуль первую и последнюю строки процедуры.
Имя процедуры может быть написано как на латинице, так и на кириллице, может содержать цифры и знак подчеркивания. Оно обязательно должно начинаться с буквы и не содержать пробелы, вместо которых следует использовать знак подчеркивания.
- Вставьте внутрь шаблона процедуры следующую строку:
MsgBox "Привет"
.
Функция MsgBox выводит информационное сообщение с указанным текстом. В нашем примере – это «Привет».
- Проверьте, что курсор находится внутри процедуры, и запустите ее, нажав клавишу «F5». А также, запустить процедуру на выполнение можно, нажав на треугольник (на изображении под пунктом меню «Debug») или на кнопку «Run Sub/UserForm» во вкладке «Run» главного меню редактора VBA Excel.
Если вы увидели такое сообщение, как на изображении, то, поздравляю – вы написали свою первую программу!
Работа с переменными
Чтобы использовать в процедуре переменные, их необходимо объявить с помощью ключевого слова «Dim». Если при объявлении переменных не указать типы данных, они смогут принимать любые доступные в VBA Excel значения. Комментарии в тексте процедур начинаются со знака «’» (апостроф).
Пример 2
Присвоение переменным числовых значений:
Public Sub Primer2() ‘Объявляем переменные x, y, z Dim x, y, z ‘Присваиваем значение переменной x x = 25 ‘Присваиваем значение переменной y y = 35 ‘Присваиваем переменной z сумму ‘значений переменных x и y z = x + y ‘Выводим информационное сообщение ‘со значением переменной z MsgBox z End Sub |
Пример 3
Присвоение переменным строковых значений:
Public Sub Primer3() ‘Объявляем переменные x, y, z Dim x, y, z ‘Присваиваем строку переменной x x = «Добрый» ‘Присваиваем строку переменной y y = «день!» ‘Присваиваем переменной z строку, ‘состоящую из строк x и y ‘с пробелом между ними z = x & » « & y ‘Выводим информационное сообщение ‘со значением переменной z MsgBox z End Sub |
Скопируйте примеры процедур в стандартный модуль и запустите их на выполнение.
Изменение содержимого ячеек
Для обозначения диапазонов, в том числе и отдельных ячеек, в VBA Excel имеется ключевое слово «Range». Ячейке A1 на рабочем листе будет соответствовать выражение Range("A1")
в коде VBA Excel.
Пример 4
Public Sub Primer4() ‘Объявляем переменную x Dim x ‘Присваиваем значение переменной x x = 125.61 ‘Присваиваем ячейке A1 ‘значение переменной x Range(«A1») = x ‘Присваиваем значение ячейке B1 Range(«B1») = 356.24 ‘Записываем в ячейку C1 ‘сумму ячеек A1 и B1 Range(«C1») = Range(«A1») + Range(«B1») End Sub |
Скопируйте процедуру этого примера в стандартный модуль и запустите на выполнение. Перейдите на активный рабочий лист Excel, чтобы увидеть результат.