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
Содержание
- Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic
- Introduction
- Prerequisites
- Learning Objectives
- Important Concepts
- What is VBA?
- Why use VBA in Excel?
- Getting Set Up to Write VBA in Excel
- Developer Tab
- VBA Editor
- Excel VBA Examples
- Example #1: Display a Message when Users Open the Excel Workbook
- How is it doing that?
- When could I use this?
- Real World Examples
- Example #2: Allow User to Execute another Procedure
- How is it doing that?
- When could I use this?
- Real World Examples
- Example #3: Add Numbers to a Range with a For-Next Loop
- How is it doing that?
- When could I use this?
- Real World Examples
- Conclusion
Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic
Introduction
This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).
Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.
- In 1996, there were over 30 million users of Microsoft Excel (source).
- Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.
We’re one big happy family!
In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.
Prerequisites
You don’t need any prior programming experience to understand this tutorial. However, you will need:
- Basic to intermediate familiarity with Microsoft Excel
- If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
- A willingness to try new things
Learning Objectives
Over the course of this article, you will learn:
- 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.
Why use VBA in Excel?
Because wood-fired pizza is the best!
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.
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.
Источник
Excel Programming (Table of Contents)
- Introduction to Programming in Excel
- How to Program in Excel?
Introduction to Programming in Excel
Have you ever been tired of doing a task in Excel which you feel can be automated and save your time? Most of the time, you must have encountered such tasks. However, in order to automate any task, you first need to have programming skills for that particular language. In Excel, you can do programming with the help of Visual Basic for Application (VBA) which is Excel’s own programming language that can help you to automate the tasks. In this article, we will see how we can do programming in Excel VBA. VBA can be used to write a program that can automate the task for you. The piece of lines we write under VBA is called Macro, which is written in such a way that they instruct the Excel system about what to be done.
How to Program in Excel?
Let’s understand how to Program in excel with few illustrations.
Enabling Developer Tab
The first thing that comes is enabling the developer tab that helps you to record and store a macro (VBA Code). Let us see how we can get that enabled.
- Navigate to the File menu in your excel file and click on it.
- Within the File menu, click on Options, and it will load a new window with all excel options available.
- In the new window that popped up named Excel Options, click on the Customize Ribbon tab. You can see all the customization options you can use for Excel Ribbon, which appears at the top of your Excel file.
- Enable Developer option under Main Tabs dropdown within Customize the Ribbon: section. You can check (tick-mark) the Developer tab to enable it. Click the OK button placed at the bottom right of the Excel Options tab, and that’s it.
- You have successfully enabled the Developer option within your excel. If you check the Excel Ribbon in your file now, you’ll be able to see a new tab added there with the name Developer on it.
This is the first step you need to follow before you start writing macros in Excel. Because the Developer tab is needed to record and run the macro, this option tab is not by default enabled, which is why we tried enabling it here first.
Recording a Macro
- Open the Excel file. Navigate towards the Developer tab you just enabled and then click on the Record Macro button, categorized and can be seen under the Code section.
- As soon as you click on the Record Macro button, you’ll see a window popping up; in that window, you must have to assign a name to the macro; you can also assign a shortcut key for this macro to run. Can you add the description, if any, for this macro you are creating? Once you are done with all this, you can click on the OK button placed at the right bottom of the window. See the screenshot below for your reference.
As soon as you click OK, the system starts recording the macro and all the tasks you perform will be recorded and converted to Excel Program in the backend.
- Try typing the sentence “This is my first VBA code, and I am very happy!” in cell A1 within the Excel sheet and press Enter key. These steps will be recorded in the backend of the macro.
- Under the Code section, you might have observed that the Record Macro button has changed to Stop Recording. This is like Play and Stop. Record Macro Works as Play button and Stop Recording work as Stop button. Click on the Stop Recording button to stop the recording.
The magic behind all this is, Excel has recorded my steps here and converted those into pieces of code so that this task can be automated. It means, every single step, selecting cell A1, inputting the text as “This is my first VBA code, and I am happy!”, clicking Enter to go to the next cell. All these steps are converted into a VBA code. Let’s check the code now.
- In order to go to Visual Basic Editor, you can click on the Visual Basic option under the Code category in the Developer tab, or you can use Alt + F11 as a shortcut for the same.
- Navigate towards the Modules section under VBAProject and click on the plus button under it to see the list of active modules in VBA.
- Inside the Modules folder, you can see Module1 as soon as you click on the plus sign. You can double click on Module1; it is where your code for the task we performed in previous steps (Step 3 and 4) are recorded. Save this code, and you can run it every time to get the same output. See the screenshot below:
Conclusion
- We can record a macro in Excel to automate day to day small tasks, which are simpler for the system to manipulate programmatically.
- The cool thing about it is you don’t need to dig your head deep for the logic behind each step you perform. Excel VBA does it for you.
- For some complex tasks, such as the one which involves looping and conditional statements, you need to write code manually under VBA.
Things to Remember About Programming in Excel
- The Developers tab is not by default enabled and visible to you in Excel Ribbon. You need to enable it through Excel Options.
- Recording a macro works on simple tasks that are repeating, and you need those to be automated. However, for complex tasks which involve looping or Conditional Inputs and Outputs are still need to be coded manually under VBA.
- You need to save the file as an Excel-Macro Enable file format in order to be able to read and run the code again on your excel.
Recommended Articles
This is a guide to Programming in Excel. Here we discuss how to Program in Excel along with practical examples and a downloadable excel template. You can also go through our other suggested articles –
- Ribbon in Excel
- TRIM Formula in Excel
- Project Management Template in Excel
- COUNTIFS in Excel
Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web More…Less
Automate your repetitive tasks with Office Scripts in Excel for the web, Windows, and Mac. Create scripts and replay them whenever you want. Share your scripts across the organization to help others make their workflows fast and consistent. Edit your scripts as your workflow changes and let the cloud update your solutions across the organization.
Create an Office Script
There are two ways to make a new Office Script.
-
Record your actions with the Action Recorder. This is great when you have consistent actions that you take on your workbooks. No coding knowledge is needed to record and share Office Scripts. Get started recording with Record your actions as Office Scripts — Microsoft Support.
-
Use the Code Editor to work with TypeScript code for advanced scripts. To learn how to start with the Action Recorder and edit scripts to better suit your needs, see the tutorial Record, edit, and create Office Scripts in Excel — Office Scripts | Microsoft Learn.
Run an Office Script
-
All the scripts you and your workbook have access to are found under Automate > All scripts. The script gallery shows the most recent scripts.
-
Select the script you want to run. It will display in the Code Editor. Select the Run button to start the script. You’ll see a brief notification that the script is running, which disappears when the script is complete.
-
More options — Select the ellipsis (…) on the right-hand side of the Code Editor pane, to see the contextual menu. Here, you have options to:
-
Rename the script
-
Make a Copy of the script
-
Share the script
-
Integrate the script with Power Automate by using Create Flow
-
Delete the script
-
Potential Errors
-
Certain actions may be fine the first time you record your script, but fail when you play it again. For instance, in the earlier example, where we formatted some sample data as a table, our code would fail if we tried to run it on the updated table, because Excel doesn’t allow tables to overlap each other. At this point, the Code Editor displays an error message.
Select the View Logs button to display a brief error explanation at the bottom of the Code Editor pane.
-
Unsupported features — We’re constantly working to add support for more features, but at this time not everything is supported. When this happens, you’ll see a note in the Record Actions pane. Such actions aren’t added to the script and will be ignored.
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
See also
Record your actions as Office Scripts
Office Scripts technical documentation
Record, edit, and create Office Scripts in Excel on the web
Troubleshooting Office Scripts
Sample scripts for Office Scripts in Excel on the web
Create a button to run an Office Script
Need more help?
Macro codes can save you a ton of time.
You can automate small as well as heavy tasks with VBA codes.
And do you know?
With the help of macros…
…you can break all the limitations of Excel which you think Excel has.
And today, I have listed some of the useful codes examples to help you become more productive in your day to day work.
You can use these codes even if you haven’t used VBA before that.
But here’s the first thing to know:
What is a Macro Code?
In Excel, macro code is a programming code which is written in VBA (Visual Basic for Applications) language.
The idea behind using a macro code is to automate an action which you perform manually in Excel, otherwise.
For example, you can use a code to print only a particular range of cells just with a single click instead of selecting the range -> File Tab -> Print -> Print Select -> OK Button.
How to use a Macro Code in Excel
Before you use these codes, make sure you have your developer tab on your Excel ribbon to access VB editor. Once you activate developer tab you can use below steps to paste a VBA code into VB editor.
List of Top 100 macro Examples (CODES) for VBA beginners
I have added all the codes into specific categories so that you can find your favorite codes quickly. Just read the title and click on it to get the code.
- This is my Ultimate VBA Library which I update on monthly basis with new codes and Don’t forget to check the VBA Examples Sectionꜜ at the end of this list.
- VBA is one of the Advanced Excel Skills.
- To manage all of these codes make sure to read about Personal Macro Workbook to use these codes in all the workbooks.
- I have tested all of these codes in different versions of Excel (2007, 2010, 2013, 2016, and 2019). If you found any error in any of these codes, make sure to share with me.
Basic Codes
These VBA codes will help you to perform some basic tasks in a flash which you frequently do in your spreadsheets.
1. Add Serial Numbers
Sub AddSerialNumbers() Dim i As Integer On Error GoTo Last i = InputBox("Enter Value", "Enter Serial Numbers") For i = 1 To i ActiveCell.Value = i ActiveCell.Offset(1, 0).Activate Next i Last:Exit Sub End Sub
This macro code will help you to automatically add serial numbers in your Excel sheet which can be helpful for you if you work with large data.
To use this code you need to select the cell from where you want to start the serial numbers and when you run this it shows you a message box where you need to enter the highest number for the serial numbers and click OK. And once you click OK, it simply runs a loop and add a list of serial numbers to the cells downward.
2. Insert Multiple Columns
Sub InsertMultipleColumns() Dim i As Integer Dim j As Integer ActiveCell.EntireColumn.Select On Error GoTo Last i = InputBox("Enter number of columns to insert", "Insert Columns") For j = 1 To i Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightorAbove Next j Last: Exit Sub End Sub
This code helps you to enter multiple columns in a single click. When you run this code it asks you the number columns you want to add and when you click OK, it adds entered number of columns after the selected cell. If you want to add columns before the selected cell, replace the xlToRight to xlToLeft in the code.
3. Insert Multiple Rows
Sub InsertMultipleRows() Dim i As Integer Dim j As Integer ActiveCell.EntireRow.Select On Error GoTo Last i = InputBox("Enter number of columns to insert", "Insert Columns") For j = 1 To i Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove Next j Last: Exit Sub End Sub
With this code, you can enter multiple rows in the worksheet. When you run this code, you can enter the number of rows to insert and make sure to select the cell from where you want to insert the new rows. If you want to add rows before the selected cell, replace the xlToDown to xlToUp in the code.
4. Auto Fit Columns
Sub AutoFitColumns() Cells.Select Cells.EntireColumn.AutoFit End Sub
This code quickly auto fits all the columns in your worksheet. So when you run this code, it will select all the cells in your worksheet and instantly auto-fit all the columns.
5. Auto Fit Rows
Sub AutoFitRows() Cells.Select Cells.EntireRow.AutoFit End Sub
You can use this code to auto-fit all the rows in a worksheet. When you run this code it will select all the cells in your worksheet and instantly auto-fit all the row.
6. Remove Text Wrap
Sub RemoveTextWrap() Range("A1").WrapText = False End Sub
This code will help you to remove text wrap from the entire worksheet with a single click. It will first select all the columns and then remove text wrap and auto fit all the rows and columns. There’s also a shortcut that you can use (Alt + H +W) for but if you add this code to Quick Access Toolbar it’s convenient than a keyboard shortcut.
7. Unmerge Cells
Sub UnmergeCells() Selection.UnMerge End Sub
This code simply uses the unmerge options which you have on the HOME tab. The benefit of using this code is you can add it to the QAT and unmerge all the cell in the selection. And if you want to un-merge a specific range you can define that range in the code by replacing the word selection.
8. Open Calculator
Sub OpenCalculator() Application.ActivateMicrosoftApp Index:=0 End Sub
In Windows, there is a specific calculator and by using this macro code you can open that calculator directly from Excel. As I mentioned that it’s for windows and if you run this code in the MAC version of VBA you’ll get an error.
9. Add Header/Footer Date
Sub DateInHeader() With ActiveSheet.PageSetup .LeftHeader = "" .CenterHeader = "&D" .RightHeader = "" .LeftFooter = "" .CenterFooter = "" .RightFooter = "" End With End Sub
This macro adds a date to the header when you run it. It simply uses the tag «&D» for adding the date. You can also change it to the footer or change the side by replacing the «» with the date tag. And if you want to add a specific date instead of the current date you can replace the «&D» tag with that date from the code.
10. Custom Header/Footer
Sub CustomHeader() Dim myText As String myText = InputBox("Enter your text here", "Enter Text") With ActiveSheet.PageSetup .LeftHeader = "" .CenterHeader = myText .RightHeader = "" .LeftFooter = "" .CenterFooter = "" .RightFooter = "" End With End Sub
When you run this code, it shows an input box that asks you to enter the text which you want to add as a header, and once you enter it click OK.
If you see this closely you have six different lines of code to choose the place for the header or footer. Let’s say if you want to add left-footer instead of center header simply replace the “myText” to that line of the code by replacing the «» from there.
Formatting Codes
These VBA codes will help you to format cells and ranges using some specific criteria and conditions.
11. Highlight Duplicates from Selection
Sub HighlightDuplicateValues() Dim myRange As Range Dim myCell As Range Set myRange = Selection For Each myCell In myRange If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then myCell.Interior.ColorIndex = 36 End If Next myCell End Sub
This macro will check each cell of your selection and highlight the duplicate values. You can also change the color from the code.
12. Highlight the Active Row and Column
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Dim strRange As String strRange = Target.Cells.Address & "," & _ Target.Cells.EntireColumn.Address & "," & _ Target.Cells.EntireRow.Address Range(strRange).Select End Sub
I really love to use this macro code whenever I have to analyze a data table. Here are the quick steps to apply this code.
- Open VBE (ALT + F11).
- Go to Project Explorer (Ctrl + R, If hidden).
- Select your workbook & double click on the name of a particular worksheet in which you want to activate the macro.
- Paste the code into it and select the “BeforeDoubleClick” from event drop down menu.
- Close VBE and you are done.
Remember that, by applying this macro you will not able to edit the cell by double click.
13. Highlight Top 10 Values
Sub TopTen() Selection.FormatConditions.AddTop10 Selection.FormatConditions(Selection.FormatConditions.Count).S tFirstPriority With Selection.FormatConditions(1) .TopBottom = xlTop10Top .Rank = 10 .Percent = False End With With Selection.FormatConditions(1).Font .Color = -16752384 .TintAndShade = 0 End With With Selection.FormatConditions(1).Interior .PatternColorIndex = xlAutomatic .Color = 13561798 .TintAndShade = 0 End With Selection.FormatConditions(1).StopIfTrue = False End Sub
Just select a range and run this macro and it will highlight top 10 values with the green color.
14. Highlight Named Ranges
Sub HighlightRanges() Dim RangeName As Name Dim HighlightRange As Range On Error Resume Next For Each RangeName In ActiveWorkbook.Names Set HighlightRange = RangeName.RefersToRange HighlightRange.Interior.ColorIndex = 36 Next RangeName End Sub
If you are not sure about how many named ranges you have in your worksheet then you can use this code to highlight all of them.
15. Highlight Greater than Values
Sub HighlightGreaterThanValues() Dim i As Integer i = InputBox("Enter Greater Than Value", "Enter Value") Selection.FormatConditions.Delete Selection.FormatConditions.Add Type:=xlCellValue, _ Operator:=xlGreater, Formula1:=i Selection.FormatConditions(Selection.FormatConditions.Count).S tFirstPriority With Selection.FormatConditions(1) .Font.Color = RGB(0, 0, 0) .Interior.Color = RGB(31, 218, 154) End With End Sub
Once you run this code it will ask you for the value from which you want to highlight all greater values.
16. Highlight Lower Than Values
Sub HighlightLowerThanValues() Dim i As Integer i = InputBox("Enter Lower Than Value", "Enter Value") Selection.FormatConditions.Delete Selection.FormatConditions.Add _ Type:=xlCellValue, _ Operator:=xlLower, _ Formula1:=i Selection.FormatConditions(Selection.FormatConditions.Count).S tFirstPriority With Selection.FormatConditions(1) .Font.Color = RGB(0, 0, 0) .Interior.Color = RGB(217, 83, 79) End With End Sub
Once you run this code it will ask you for the value from which you want to highlight all lower values.
17. Highlight Negative Numbers
Sub highlightNegativeNumbers() Dim Rng As Range For Each Rng In Selection If WorksheetFunction.IsNumber(Rng) Then If Rng.Value < 0 Then Rng.Font.Color= -16776961 End If End If Next End Sub
Select a range of cells and run this code. It will check each cell from the range and highlight all cells the where you have a negative number.
18. Highlight Specific Text
Sub highlightValue() Dim myStr As String Dim myRg As range Dim myTxt As String Dim myCell As range Dim myChar As String Dim I As Long Dim J As Long On Error Resume Next If ActiveWindow.RangeSelection.Count > 1 Then myTxt = ActiveWindow.RangeSelection.AddressLocal Else myTxt = ActiveSheet.UsedRange.AddressLocal End If LInput: Set myRg = _ Application.InputBox _ ("please select the data range:", "Selection Required", myTxt, , , , , 8) If myRg Is Nothing Then Exit Sub If myRg.Areas.Count > 1 Then MsgBox "not support multiple columns" GoTo LInput End If If myRg.Columns.Count <> 2 Then MsgBox "the selected range can only contain two columns " GoTo LInput End If For I = 0 To myRg.Rows.Count - 1 myStr = myRg.range("B1").Offset(I, 0).Value With myRg.range("A1").Offset(I, 0) .Font.ColorIndex = 1 For J = 1 To Len(.Text) Mid(.Text, J, Len(myStr)) = myStrThen .Characters(J, Len(myStr)).Font.ColorIndex = 3 Next End With Next I End Sub
Suppose you have a large data set and you want to check for a particular value. For this, you can use this code. When you run it, you will get an input box to enter the value to search for.
19. Highlight Cells with Comments
Sub highlightCommentCells() Selection.SpecialCells(xlCellTypeComments).Select Selection.Style= "Note" End Sub
To highlight all the cells with comments use this macro.
20. Highlight Alternate Rows in the Selection
Sub highlightAlternateRows() Dim rng As Range For Each rng In Selection.Rows If rng.Row Mod 2 = 1 Then rng.Style = "20% -Accent1" rng.Value = rng ^ (1 / 3) Else End If Next rng End Sub
By highlighting alternate rows you can make your data easily readable, and for this, you can use below VBA code. It will simply highlight every alternate row in selected range.
21. Highlight Cells with Misspelled Words
Sub HighlightMisspelledCells() Dim rng As Range For Each rng In ActiveSheet.UsedRange If Not Application.CheckSpelling(word:=rng.Text) Then rng.Style = "Bad" End If Next rng End Sub
If you find hard to check all the cells for spelling error then this code is for you. It will check each cell from the selection and highlight the cell where is a misspelled word.
22. Highlight Cells With Error in the Entire Worksheet
Sub highlightErrors() Dim rng As Range Dim i As Integer For Each rng In ActiveSheet.UsedRange If WorksheetFunction.IsError(rng) Then i = i + 1 rng.Style = "bad" End If Next rng MsgBox _ "There are total " & i _ & " error(s) in this worksheet." End Sub
To highlight and count all the cells in which you have an error, this code will help you. Just run this code and it will return a message with the number error cells and highlight all the cells.
23. Highlight Cells with a Specific Text in Worksheet
Sub highlightSpecificValues() Dim rng As range Dim i As Integer Dim c As Variant c = InputBox("Enter Value To Highlight") For Each rng In ActiveSheet.UsedRange If rng = c Then rng.Style = "Note" i = i + 1 End If Next rng MsgBox "There are total " & i & " " & c & " in this worksheet." End Sub
This code will help you to count the cells which have a specific value which you will mention and after that highlight all those cells.
24. Highlight all the Blank Cells Invisible Space
Sub blankWithSpace() Dim rng As Range For Each rng In ActiveSheet.UsedRange If rng.Value = " " Then rng.Style = "Note" End If Next rng End Sub
Sometimes there are some cells which are blank but they have a single space and due to this, it’s really hard to identify them. This code will check all the cell in the worksheet and highlight all the cells which have a single space.
25. Highlight Max Value In The Range
Sub highlightMaxValue() Dim rng As Range For Each rng In Selection If rng = WorksheetFunction.Max(Selection) Then rng.Style = "Good" End If Next rng End Sub
It will check all the selected cells and highlight the cell with the maximum value.
26. Highlight Min Value In The Range
Sub Highlight_Min_Value() Dim rng As Range For Each rng In Selection If rng = WorksheetFunction.Min(Selection) Then rng.Style = "Good" End If Next rng End Sub
It will check all the selected cells and highlight the cell with the Minimum value.
27. Highlight Unique Values
Sub highlightUniqueValues() Dim rng As Range Set rng = Selection rng.FormatConditions.Delete Dim uv As UniqueValues Set uv = rng.FormatConditions.AddUniqueValues uv.DupeUnique = xlUnique uv.Interior.Color = vbGreen End Sub
This codes will highlight all the cells from the selection which has a unique value.
28. Highlight Difference in Columns
Sub columnDifference() Range("H7:H8,I7:I8").Select Selection.ColumnDifferences(ActiveCell).Select Selection.Style= "Bad" End Sub
Using this code you can highlight the difference between two columns (corresponding cells).
29. Highlight Difference in Rows
Sub rowDifference() Range("H7:H8,I7:I8").Select Selection.RowDifferences(ActiveCell).Select Selection.Style= "Bad" End Sub
And by using this code you can highlight difference between two row (corresponding cells).
Printing Codes
These macro codes will help you to automate some printing tasks which can further save you a ton of time.
30. Print Comments
Sub printComments() With ActiveSheet.PageSetup .printComments = xlPrintSheetEnd End With End Sub
Use this macro to activate settings to print cell comments in the end of the page. Let’s say you have 10 pages to print, after using this code you will get all the comments on 11th last page.
31. Print Narrow Margin
Sub printNarrowMargin() With ActiveSheet.PageSetup .LeftMargin = Application .InchesToPoints (0.25) .RightMargin = Application.InchesToPoints(0.25) .TopMargin = Application.InchesToPoints(0.75) .BottomMargin = Application.InchesToPoints(0.75) .HeaderMargin = Application.InchesToPoints(0.3) .FooterMargin = Application.InchesToPoints(0.3) End With ActiveWindow.SelectedSheets.PrintOut _ Copies:=1, _ Collate:=True, _ IgnorePrintAreas:=False End Sub
Use this VBA code to take a print with a narrow margin. When you run this macro it will automatically change margins to narrow.
32. Print Selection
Sub printSelection() Selection.PrintOut Copies:=1, Collate:=True End Sub
This code will help you print selected range. You don’t need to go to printing options and set printing range. Just select a range and run this code.
33. Print Custom Pages
Sub printCustomSelection() Dim startpage As Integer Dim endpage As Integer startpage = _ InputBox("Please Enter Start Page number.", "Enter Value") If Not WorksheetFunction.IsNumber(startpage) Then MsgBox _ "Invalid Start Page number. Please try again.", "Error" Exit Sub End If endpage = _ InputBox("Please Enter End Page number.", "Enter Value") If Not WorksheetFunction.IsNumber(endpage) Then MsgBox _ "Invalid End Page number. Please try again.", "Error" Exit Sub End If Selection.PrintOut From:=startpage, _ To:=endpage, Copies:=1, Collate:=True End Sub
Instead of using the setting from print options you can use this code to print custom page range. Let’s say you want to print pages from 5 to 10. You just need to run this VBA code and enter start page and end page.
Worksheet Codes
These macro codes will help you to control and manage worksheets in an easy way and save your a lot of time.
34. Hide all but the Active Worksheet
Sub HideWorksheet() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If ws.Name <> ThisWorkbook.ActiveSheet.Name Then ws.Visible = xlSheetHidden End If Next ws End Sub
Now, let’s say if you want to hide all the worksheets in your workbook other than the active worksheet. This macro code will do this for you.
35. Unhide all Hidden Worksheets
Sub UnhideAllWorksheet() Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets ws.Visible = xlSheetVisible Next ws End Sub
And if you want to un-hide all the worksheets which you have hide with previous code, here is the code for that.
36. Delete all but the Active Worksheet
Sub DeleteWorksheets() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If ws.name <> ThisWorkbook.ActiveSheet.name Then Application.DisplayAlerts = False ws.Delete Application.DisplayAlerts = True End If Next ws End Sub
If you want to delete all the worksheets other than the active sheet, this macro is useful for you. When you run this macro it will compare the name of the active worksheet with other worksheets and then delete them.
37. Protect all Worksheets Instantly
Sub ProtectAllWorskeets() Dim ws As Worksheet Dim ps As String ps = InputBox("Enter a Password.", vbOKCancel) For Each ws In ActiveWorkbook.Worksheets ws.Protect Password:=ps Next ws End Sub
If you want to protect your all worksheets in one go here is a code for you. When you run this macro, you will get an input box to enter a password. Once you enter your password, click OK. And make sure to take care about CAPS.
38. Resize All Charts in a Worksheet
Sub Resize_Charts() Dim i As Integer For i = 1 To ActiveSheet.ChartObjects.Count With ActiveSheet.ChartObjects(i) .Width = 300 .Height = 200 End With Next i End Sub
Make all chart same in size. This macro code will help you to make all the charts of the same size. You can change the height and width of charts by changing it in macro code.
39. Insert Multiple Worksheets
Sub InsertMultipleSheets() Dim i As Integer i = _ InputBox("Enter number of sheets to insert.", _ "Enter Multiple Sheets") Sheets.Add After:=ActiveSheet, Count:=i End Sub
You can use this code if you want to add multiple worksheets in your workbook in a single shot. When you run this macro code you will get an input box to enter the total number of sheets you want to enter.
40. Protect Worksheet
Sub ProtectWS() ActiveSheet.Protect "mypassword", True, True End Sub
If you want to protect your worksheet you can use this macro code. All you have to do just mention your password in the code.
41. Un-Protect Worksheet
Sub UnprotectWS() ActiveSheet.Unprotect "mypassword" End Sub
If you want to unprotect your worksheet you can use this macro code. All you have to do just mention your password which you have used while protecting your worksheet.
42. Sort Worksheets
Sub SortWorksheets() Dim i As Integer Dim j As Integer Dim iAnswer As VbMsgBoxResult iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _ & "Clicking No will sort in Descending Order", _ vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets") For i = 1 To Sheets.Count For j = 1 To Sheets.Count - 1 If iAnswer = vbYes Then If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then Sheets(j).Move After:=Sheets(j + 1) End If ElseIf iAnswer = vbNo Then If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then Sheets(j).Move After:=Sheets(j + 1) End If End If Next j Next i End Sub
This code will help you to sort worksheets in your workbook according to their name.
43. Protect all the Cells With Formulas
Sub lockCellsWithFormulas() With ActiveSheet .Unprotect .Cells.Locked = False .Cells.SpecialCells(xlCellTypeFormulas).Locked = True .Protect AllowDeletingRows:=True End With End Sub
To protect cell with formula with a single click you can use this code.
44. Delete all Blank Worksheets
Sub deleteBlankWorksheets() Dim Ws As Worksheet On Error Resume Next Application.ScreenUpdating= False Application.DisplayAlerts= False For Each Ws In Application.Worksheets If Application.WorksheetFunction.CountA(Ws.UsedRange) = 0 Then Ws.Delete End If Next Application.ScreenUpdating= True Application.DisplayAlerts= True End Sub
Run this code and it will check all the worksheets in the active workbook and delete if a worksheet is blank.
45. Unhide all Rows and Columns
Sub UnhideRowsColumns() Columns.EntireColumn.Hidden = False Rows.EntireRow.Hidden = False End Sub
Instead of unhiding rows and columns on by one manually you can use this code to do this in a single go.
46. Save Each Worksheet as a Single PDF
Sub SaveWorkshetAsPDF() Dimws As Worksheet For Each ws In Worksheets ws.ExportAsFixedFormat _ xlTypePDF, _ "ENTER-FOLDER-NAME-HERE" & _ ws.Name & ".pdf" Next ws End Sub
This code will simply save all the worksheets in a separate PDF file. You just need to change the folder name from the code.
47. Disable Page Breaks
Sub DisablePageBreaks() Dim wb As Workbook Dim wks As Worksheet Application.ScreenUpdating = False For Each wb In Application.Workbooks For Each Sht In wb.Worksheets Sht.DisplayPageBreaks = False Next Sht Next wb Application.ScreenUpdating = True End Sub
To disable page breaks use this code. It will simply disable page breaks from all the open workbooks.
Workbook Codes
These codes will help you to perform workbook level tasks in an easy way and with minimum efforts.
48. Create a Backup of a Current Workbook
Sub FileBackUp() ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _ "" & Format(Date, "mm-dd-yy") & " " & _ ThisWorkbook.name End Sub
This is one of the most useful macros which can help you to save a backup file of your current workbook.
It will save a backup file in the same directory where your current file is saved and it will also add the current date with the name of the file.
49. Close all Workbooks at Once
Sub CloseAllWorkbooks() Dim wbs As Workbook For Each wbs In Workbooks wbs.Close SaveChanges:=True Next wb End Sub
Use this macro code to close all open workbooks. This macro code will first check all the workbooks one by one and close them. If any of the worksheets is not saved, you’ll get a message to save it.
50. Copy Active Worksheet into a New Workbook
Sub CopyWorksheetToNewWorkbook() ThisWorkbook.ActiveSheet.Copy _ Before:=Workbooks.Add.Worksheets(1) End Sub
Let’s say if you want to copy your active worksheet in a new workbook, just run this macro code and it will do the same for you. It’s a super time saver.
51. Active Workbook in an Email
Sub Send_Mail() Dim OutApp As Object Dim OutMail As Object Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) With OutMail .to = "Sales@FrontLinePaper.com" .Subject = "Growth Report" .Body = "Hello Team, Please find attached Growth Report." .Attachments.Add ActiveWorkbook.FullName .display End With Set OutMail = Nothing Set OutApp = Nothing End Sub
Use this macro code to quickly send your active workbook in an e-mail. You can change the subject, email, and body text in code and if you want to send this mail directly, use «.Send» instead of «.Display».
52. Add Workbook to a Mail Attachment
Sub OpenWorkbookAsAttachment() Application.Dialogs(xlDialogSendMail).Show End Sub
Once you run this macro it will open your default mail client and attached active workbook with it as an attachment.
53. Welcome Message
Sub auto_open() MsgBox _ "Welcome To ExcelChamps & Thanks for downloading this file." End Sub
You can use auto_open to perform a task on opening a file and all you have to do just name your macro «auto_open».
54. Closing Message
Sub auto_close() MsgBox "Bye Bye! Don't forget to check other cool stuff on excelchamps.com" End Sub
You can use close_open to perform a task on opening a file and all you have to do just name your macro «close_open».
55. Count Open Unsaved Workbooks
Sub VisibleWorkbooks() Dim book As Workbook Dim i As Integer For Each book In Workbooks If book.Saved = False Then i = i + 1 End If Next book MsgBox i End Sub
Let’s you have 5-10 open workbooks, you can use this code to get the number of workbooks which are not saved yet.
Pivot Table Codes
These codes will help you to manage and make some changes in pivot tables in a flash.
56. Hide Pivot Table Subtotals
Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField On Error Resume Next Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name) If pt Is Nothing Then MsgBox "You must place your cursor inside of a PivotTable." Exit Sub End If For Each pf In pt.PivotFields pf.Subtotals(1) = True pf.Subtotals(1) = False Next pf End Sub
If you want to hide all the subtotals, just run this code. First of all, make sure to select a cell from your pivot table and then run this macro.
57. Refresh All Pivot Tables
Sub vba_referesh_all_pivots() Dim pt As PivotTable For Each pt In ActiveWorkbook.PivotTables pt.RefreshTable Next pt End Sub
A super quick method to refresh all pivot tables. Just run this code and all of your pivot tables in your workbook will be refresh in a single shot.
58. Create a Pivot Table
Follow this step by step guide to create a pivot table using VBA.
59. Auto Update Pivot Table Range
Sub UpdatePivotTableRange() Dim Data_Sheet As Worksheet Dim Pivot_Sheet As Worksheet Dim StartPoint As Range Dim DataRange As Range Dim PivotName As String Dim NewRange As String Dim LastCol As Long Dim lastRow As Long 'Set Pivot Table & Source Worksheet Set Data_Sheet = ThisWorkbook.Worksheets("PivotTableData3") Set Pivot_Sheet = ThisWorkbook.Worksheets("Pivot3") 'Enter in Pivot Table Name PivotName = "PivotTable2" 'Defining Staring Point & Dynamic Range Data_Sheet.Activate Set StartPoint = Data_Sheet.Range("A1") LastCol = StartPoint.End(xlToRight).Column DownCell = StartPoint.End(xlDown).Row Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol)) NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1) 'Change Pivot Table Data Source Range Address Pivot_Sheet.PivotTables(PivotName). _ ChangePivotCache ActiveWorkbook. _ PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange) 'Ensure Pivot Table is Refreshed Pivot_Sheet.PivotTables(PivotName).RefreshTable 'Complete Message Pivot_Sheet.Activate MsgBox "Your Pivot Table is now updated." End Sub
If you are not using Excel tables then you can use this code to update pivot table range.
60. Disable/Enable Get Pivot Data
Sub activateGetPivotData() Application.GenerateGetPivotData = True End Sub Sub deactivateGetPivotData() Application.GenerateGetPivotData = False End Sub
To disable/enable GetPivotData function you need to use Excel option. But with this code you can do it in a single click.
Charts Codes
Use these VBA codes to manage charts in Excel and save your lot of time.
61. Change Chart Type
Sub ChangeChartType() ActiveChart.ChartType = xlColumnClustered End Sub
This code will help you to convert chart type without using chart options from the tab. All you have to do just specify to which type you want to convert.
Below code will convert selected chart to a clustered column chart. There are different codes for different types, you can find all those types from here.
62. Paste Chart as an Image
Sub ConvertChartToPicture() ActiveChart.ChartArea.Copy ActiveSheet.Range("A1").Select ActiveSheet.Pictures.Paste.Select End Sub
This code will help you to convert your chart into an image. You just need to select your chart and run this code.
63. Add Chart Title
Sub AddChartTitle() Dim i As Variant i = InputBox("Please enter your chart title", "Chart Title") On Error GoTo Last ActiveChart.SetElement (msoElementChartTitleAboveChart) ActiveChart.ChartTitle.Text = i Last: Exit Sub End Sub
First of all, you need to select your chart and the run this code. You will get an input box to enter chart title.
Advanced Codes
Some of the codes which you can use to preform advanced task in your spreadsheets.
64. Save Selected Range as a PDF
Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField On Error Resume Next Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.name) If pt Is Nothing Then MsgBox "You must place your cursor inside of a PivotTable." Exit Sub End If For Each pf In pt.PivotFields pf.Subtotals(1) = True pf.Subtotals(1) = False Next pf End Sub
If you want to hide all the subtotals, just run this code. First of all, make sure to select a cell from your pivot table and then run this macro.
65. Create a Table of Content
Sub TableofContent() Dim i As Long On Error Resume Next Application.DisplayAlerts = False Worksheets("Table of Content").Delete Application.DisplayAlerts = True On Error GoTo 0 ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1) ActiveSheet.Name = "Table of Content" For i = 1 To Sheets.Count With ActiveSheet .Hyperlinks.Add _ Anchor:=ActiveSheet.Cells(i, 1), _ Address:="", _ SubAddress:="'" & Sheets(i).Name & "'!A1", _ ScreenTip:=Sheets(i).Name, _ TextToDisplay:=Sheets(i).Name End With Next i End Sub
Let’s say you have more than 100 worksheets in your workbook and it’s hard to navigate now.
Don’t worry this macro code will rescue everything. When you run this code it will create a new worksheet and create a index of worksheets with a hyperlink to them.
66. Convert Range into an Image
Sub PasteAsPicture() Application.CutCopyMode = False Selection.Copy ActiveSheet.Pictures.Paste.Select End Sub
Paste selected range as an image. You just have to select the range and once you run this code it will automatically insert a picture for that range.
67. Insert a Linked Picture
Sub LinkedPicture() Selection.Copy ActiveSheet.Pictures.Paste(Link:=True).Select End Sub
This VBA code will convert your selected range into a linked picture and you can use that image anywhere you want.
68. Use Text to Speech
Sub Speak() Selection.Speak End Sub
Just select a range and run this code. Excel will speak all the text what you have in that range, cell by cell.
69. Activate Data Entry Form
Sub DataForm() ActiveSheet.ShowDataForm End Sub
There is a default data entry form which you can use for data entry.
70. Use Goal Seek
Sub GoalSeekVBA() Dim Target As Long On Error GoTo Errorhandler Target = InputBox("Enter the required value", "Enter Value") Worksheets("Goal_Seek").Activate With ActiveSheet.Range("C7") .GoalSeek_ Goal:=Target, _ ChangingCell:=Range("C2") End With Exit Sub Errorhandler: MsgBox ("Sorry, value is not valid.") End Sub
Goal Seek can be super helpful for you to solve complex problems. Learn more about goal seek from here before you use this code.
71. VBA Code to Search on Google
Sub SearchWindow32() Dim chromePath As String Dim search_string As String Dim query As String query = InputBox("Enter here your search here", "Google Search") search_string = query search_string = Replace(search_string, " ", "+") 'Uncomment the following line for Windows 64 versions and comment out Windows 32 versions' 'chromePath = "C:Program FilesGoogleChromeApplicationchrome.exe" 'Uncomment the following line for Windows 32 versions and comment out Windows 64 versions 'chromePath = "C:Program Files (x86)GoogleChromeApplicationchrome.exe" Shell (chromePath & " -url http://google.com/#q=" & search_string) End Sub
Formula Codes
These codes will help you to calculate or get results which often you do with worksheet functions and formulas.
72. Convert all Formulas into Values
Sub convertToValues() Dim MyRange As Range Dim MyCell As Range Select Case _ MsgBox("You Can't Undo This Action. " _ & "Save Workbook First?", vbYesNoCancel, _ "Alert") Case Is = vbYes ThisWorkbook.Save Case Is = vbCancel Exit Sub End Select Set MyRange = Selection For Each MyCell In MyRange If MyCell.HasFormula Then MyCell.Formula = MyCell.Value End If Next MyCell End Sub
Simply convert formulas into values. When you run this macro it will quickly change the formulas into absolute values.
73. Remove Spaces from Selected Cells
Sub RemoveSpaces() Dim myRange As Range Dim myCell As Range Select Case MsgBox("You Can't Undo This Action. " _ & "Save Workbook First?", _ vbYesNoCancel, "Alert") Case Is = vbYesThisWorkbook.Save Case Is = vbCancel Exit Sub End Select Set myRange = Selection For Each myCell In myRange If Not IsEmpty(myCell) Then myCell = Trim(myCell) End If Next myCell End Sub
One of the most useful macros from this list. It will check your selection and then remove all the extra spaces from that.
74. Remove Characters from a String
Public Function removeFirstC(rng As String, cnt As Long) removeFirstC = Right(rng, Len(rng) - cnt) End Function
Simply remove characters from the starting of a text string. All you need is to refer to a cell or insert a text into the function and number of characters to remove from the text string.
It has two arguments «rng» for the text string and «cnt» for the count of characters to remove. For Example: If you want to remove first characters from a cell, you need to enter 1 in cnt.
75. Add Insert Degree Symbol in Excel
Sub degreeSymbol( ) Dim rng As Range For Each rng In Selection rng.Select If ActiveCell <> "" Then If IsNumeric(ActiveCell.Value) Then ActiveCell.Value = ActiveCell.Value & "°" End If End If Next End Sub
Let’s say you have a list of numbers in a column and you want to add degree symbol with all of them.
76. Reverse Text
Public Function rvrse(ByVal cell As Range) As String rvrse = VBA.strReverse(cell.Value) End Function
All you have to do just enter «rvrse» function in a cell and refer to the cell in which you have text which you want to reverse.
77. Activate R1C1 Reference Style
Sub ActivateR1C1() If Application.ReferenceStyle = xlA1 Then Application.ReferenceStyle = xlR1C1 Else Application.ReferenceStyle = xlR1C1 End If End Sub
This macro code will help you to activate R1C1 reference style without using Excel options.
78. Activate A1 Reference Style
Sub ActivateA1() If Application.ReferenceStyle = xlR1C1 Then Application.ReferenceStyle = xlA1 Else Application.ReferenceStyle = xlA1 End If End Sub
This macro code will help you to activate A1 reference style without using Excel options.
79. Insert Time Range
Sub TimeStamp() Dim i As Integer For i = 1 To 24 ActiveCell.FormulaR1C1 = i & ":00" ActiveCell.NumberFormat = "[$-409]h:mm AM/PM;@" ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select Next i End Sub
With this code, you can insert a time range in sequence from 00:00 to 23:00.
80. Convert Date into Day
Sub date2day() Dim tempCell As Range Selection.Value = Selection.Value For Each tempCell In Selection If IsDate(tempCell) = True Then With tempCell .Value = Day(tempCell) .NumberFormat = "0" End With End If Next tempCell End Sub
If you have dates in your worksheet and you want to convert all those dates into days then this code is for you. Simply select the range of cells and run this macro.
81. Convert Date into Year
Sub date2year() Dim tempCell As Range Selection.Value = Selection.Value For Each tempCell In Selection If IsDate(tempCell) = True Then With tempCell .Value = Year(tempCell) .NumberFormat = "0" End With End If Next tempCell End Sub
This code will convert dates into years.
82. Remove Time from Date
Sub removeTime() Dim Rng As Range For Each Rng In Selection If IsDate(Rng) = True Then Rng.Value = VBA.Int(Rng.Value) End If Next Selection.NumberFormat = "dd-mmm-yy" End Sub
If you have time with the date and you want to remove it then you can use this code.
83. Remove Date from Date and Time
Sub removeDate() Dim Rng As Range For Each Rng In Selection If IsDate(Rng) = True Then Rng.Value = Rng.Value - VBA.Fix(Rng.Value) End If NextSelection.NumberFormat = "hh:mm:ss am/pm" End Sub
It will return only time from a date and time value.
84. Convert to Upper Case
Sub convertUpperCase() Dim Rng As Range For Each Rng In Selection If Application.WorksheetFunction.IsText(Rng) Then Rng.Value = UCase(Rng) End If Next End Sub
Select the cells and run this code. It will check each and every cell of selected range and then convert it into upper case text.
85. Convert to Lower Case
Sub convertLowerCase() Dim Rng As Range For Each Rng In Selection If Application.WorksheetFunction.IsText(Rng) Then Rng.Value= LCase(Rng) End If Next End Sub
This code will help you to convert selected text into lower case text. Just select a range of cells where you have text and run this code. If a cell has a number or any value other than text that value will remain same.
86. Convert to Proper Case
Sub convertProperCase() Dim Rng As Range For Each Rng In Selection If WorksheetFunction.IsText(Rng) Then Rng.Value = WorksheetFunction.Proper(Rng.Value) End If Next End Sub
And this code will convert selected text into the proper case where you have the first letter in capital and rest in small.
87. Convert to Sentence Case
Sub convertTextCase() Dim Rng As Range For Each Rng In Selection If WorksheetFunction.IsText(Rng) Then Rng.Value = UCase(Left(Rng, 1)) & LCase(Right(Rng, Len(Rng) - 1)) End If Next Rng End Sub
In text case, you have the first letter of the first word in capital and rest all in words in small for a single sentence and this code will help you convert normal text into sentence case.
88. Remove a Character from Selection
Sub removeChar() Dim Rng As Range Dim rc As String rc = InputBox("Character(s) to Replace", "Enter Value") For Each Rng In Selection Selection.Replace What:=rc, Replacement:="" Next End Sub
To remove a particular character from a selected cell you can use this code. It will show you an input box to enter the character you want to remove.
89. Word Count from Entire Worksheet
Sub Word_Count_Worksheet() Dim WordCnt As Long Dim rng As Range Dim S As String Dim N As Long For Each rng In ActiveSheet.UsedRange.Cells S = Application.WorksheetFunction.Trim(rng.Text) N = 0 If S <> vbNullString Then N = Len(S) - Len(Replace(S, " ", "")) + 1 End If WordCnt = WordCnt + N Next rng MsgBox "There are total " _ & Format(WordCnt, "#,##0") & _ " words in the active worksheet" End Sub
It can help you to count all the words from a worksheet.
90. Remove the Apostrophe from a Number
Sub removeApostrophes() Selection.Value = Selection.Value End Sub
If you have numeric data where you have an apostrophe before each number, you run this code to remove it.
91. Remove Decimals from Numbers
Sub removeDecimals() Dim lnumber As Double Dim lResult As Long Dim rng As Range For Each rng In Selection rng.Value = Int(rng) rng.NumberFormat = "0" Next rng End Sub
This code will simply help you to remove all the decimals from the numbers from the selected range.
92. Multiply all the Values by a Number
Sub addNumber() Dim rng As Range Dim i As Integer i = InputBox("Enter number to multiple", "Input Required") For Each rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = rng + i Else End If Next rng End Sub
Let’s you have a list of numbers and you want to multiply all the number with a particular. To use this code: Select that range of cells and run this code. It will first ask you for the number with whom you want to multiple and then instantly multiply all the numbers with it.
93. Add a Number in all the Numbers
Sub addNumber() Dim rng As Range Dim i As Integer i = InputBox("Enter number to multiple", "Input Required") For Each rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = rng + i Else End If Next rng End Sub
Just like multiplying you can also add a number into a set of numbers.
94. Calculate the Square Root
Sub getSquareRoot() Dim rng As Range Dim i As Integer For Each rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = Sqr(rng) Else End If Next rng End Sub
To calculate square root without applying a formula you can use this code. It will simply check all the selected cells and convert numbers to their square root.
95. Calculate the Cube Root
Sub getCubeRoot() Dim rng As Range Dimi As Integer For Each rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = rng ^ (1 / 3) Else End If Nextrng End Sub
To calculate cube root without applying a formula you can use this code. It will simply check all the selected cells and convert numbers to their cube root.
96. Add A-Z Alphabets in a Range
Sub addsAlphabets1() Dim i As Integer For i = 65 To 90 ActiveCell.Value = Chr(i) ActiveCell.Offset(1, 0).Select Next i End Sub
Sub addsAlphabets2() Dim i As Integer For i = 97 To 122 ActiveCell.Value = Chr(i) ActiveCell.Offset(1, 0).Select Next i End Sub
Just like serial numbers you can also insert alphabets in your worksheet. Beloware the code which you can use.
97. Convert Roman Numbers into Arabic Numbers
Sub convertToNumbers() Dim rng As Range Selection.Value = Selection.Value For Each rng In Selection If Not WorksheetFunction.IsNonText(rng) Then rng.Value = WorksheetFunction.Arabic(rng) End If Next rng End Sub
Sometimes it’s really hard to understand Roman numbers as serial numbers. This code will help you to convert roman numbers into Arabic numbers.
98. Remove Negative Signs
Sub removeNegativeSign() Dim rng As Range Selection.Value = Selection.Value For Each rng In Selection If WorksheetFunction.IsNumber(rng) Then rng.Value = Abs(rng) End If Next rng
This code will simply check all the cell in the selection and convert all the negative numbers into positive. Just select a range and run this code.
99. Replace Blank Cells with Zeros
Sub replaceBlankWithZero() Dim rng As Range Selection.Value = Selection.Value For Each rng In Selection If rng = "" Or rng = " " Then rng.Value = "0" Else End If Next rng End Sub
For data where you have blank cells, you can use the below code to add zeros in all those cells. It makes easier to use those cells in further calculations.
More Codes
100. More VBA Examples and Tutorials
- User Defined Function [UDF] in Excel using VBA
- VBA Interview Questions
- Add a Comment in a VBA Code (Macro)
- Add a Line Break in a VBA Code (Single Line into Several Lines)
- Add a New Line (Carriage Return) in a String in VBA
- Personal Macro Workbook (personal.xlsb)
- Record a Macro in Excel
- VBA Exit Sub Statement
- VBA Immediate Window (Debug.Print)
- VBA Module
- VBA MSGBOX
- VBA Objects
- VBA With Statement
- Count Rows using VBA
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- How to SELECT ALL the Cells in a Worksheet using a VBA Code
- use ActiveCell in VBA in Excel
- How to use Special Cells Method in VBA in Excel
- How to use UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- How to CLEAR an Entire Sheet using VBA in Excel
- How to Copy and Move a Sheet in Excel using VBA
- How to COUNT Sheets using VBA in Excel
- How to DELETE a SHEET using VBA in Excel
- How to Hide & Unhide a Sheet using VBA in Excel
- How to PROTECT and UNPROTECT a Sheet using VBA in Excel
- RENAME a Sheet using VBA
- Write a VBA Code to Create a New Sheet
- VBA Worksheet Object
- Activate a Sheet using VBA
- Copy an Excel File (Workbook)
- VBA Activate Workbook (Excel File)
- VBA Close Workbook (Excel File)
- VBA Combine Workbooks (Excel Files)
- VBA Create New Workbook (Excel File)
- VBA Delete Workbook (Excel File)
- VBA Open Workbook (Excel File)
- VBA Protect/Unprotect Workbook (Excel File)
- VBA Rename Workbook (Excel File)
- VBA Save Workbook (Excel File)
- VBA ThisWorkbook (Current Excel File)
- VBA Workbook
- Declare Global Variable (Public) in VBA
- Range or a Cell as a Variable in VBA
- Option Explicit Statement in VBA
- Variable in a Message Box
- VBA Constants
- VBA Dim Statement
- VBA Variables (Declare, Data Types, and Scope)
- VBA Add New Value to the Array
- VBA Array
- VBA Array Length (Size)
- VBA Array with Strings
- VBA Clear Array (Erase)
- VBA Dynamic Array
- VBA Loop Through an Array
- VBA Multi-Dimensional Array
- VBA Range to an Array
- VBA Search for a Value in an Array
- VBA Sort Array
- How to Average Values in Excel using VBA
- Get Today’s Date and Current Time using VBA
- Sum Values in Excel using VBA
- Match Function in VBA
- MOD in VBA
- Random Number
- VBA Calculate (Cell, Range, Row, & Workbook)
- VBA Concatenate
- VBA Worksheet Function (Use Excel Functions in a Macro)
- How to Check IF a Sheet Exists using VBA in Excel
- VBA Check IF a Cell is Empty + Multiple Cells
- VBA Check IF a Workbook Exists in a Folder (Excel File)
- VBA Check IF a Workbook is Open (Excel File)
- VBA Exit IF
- VBA IF – IF Then Else Statement
- VBA IF And (Test Multiple Conditions)
- VBA IF Not
- VBA IF OR (Test Multiple Conditions)
- VBA Nested IF
- VBA SELECT CASE Statement (Test Multiple Conditions)
- VBA Automation Error (Error 440)
- VBA Error 400
- VBA ERROR Handling
- VBA Invalid Procedure Call Or Argument Error (Error 5)
- VBA Object Doesn’t Support this Property or Method Error (Error 438)
- VBA Object Required Error (Error 424)
- VBA Out of Memory Error (Error 7)
- VBA Overflow Error (Error 6)
- VBA Runtime Error (Error 1004)
- VBA Subscript Out of Range Runtime Error (Error 9)
- VBA Type Mismatch Error (Error 13)
- Excel VBA Do While Loop and (Do Loop While)
- How to Loop Through All the Sheets using VBA
- Loop Through a Range using VBA
- VBA FOR LOOP
- VBA GoTo Statement
- Input Box in VBA
- VBA Create and Write to a Text File
- VBA ScreenUpdating
- VBA Status Bar
- VBA Wait and Sleep
About the Author
Puneet is using Excel since his college days. He helped thousands of people to understand the power of the spreadsheets and learn Microsoft Excel. You can find him online, tweeting about Excel, on a running track, or sometimes hiking up a mountain.
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
Explore the 40 most popular pages in this section. Below you can find a description of each page. Happy learning!
1 Run Code from a Module: As a beginner to Excel VBA, you might find it difficult to decide where to put your VBA code. This example teaches you how to run code from a module.
2 Macro Recorder: The Macro Recorder, a very useful tool included in Excel VBA, records every task you perform with Excel. All you have to do is record a specific task once. Next, you can execute the task over and over with the click of a button.
3 Add a Macro to the Toolbar: If you use an Excel macro frequently, you can add it to the Quick Access Toolbar. This way you can quickly access your macro.
4 InputBox Function: You can use the InputBox function in Excel VBA to prompt the user to enter a value.
5 Close and Open: The Close and Open Method in Excel VBA can be used to close and open workbooks. Remember, the Workbooks collection contains all the Workbook objects that are currently open.
6 Files in a Directory: Use Excel VBA to loop through all closed workbooks and worksheets in a directory and display all the names.
7 Import Sheets: In this example, we will create a VBA macro that imports sheets from other Excel files into one Excel file.
8 Programming Charts: Use Excel VBA to create two programs. One program loops through all charts on a sheet and changes each chart to a pie chart. The other program changes some properties of the first chart.
9 CurrentRegion: You can use the CurrentRegion property in Excel VBA to return the range bounded by any combination of blank rows and blank columns.
10 Entire Rows and Columns: This example teaches you how to select entire rows and columns in Excel VBA. Are you ready?
11 Offset: The Offset property in Excel VBA takes the range which is a particular number of rows and columns away from a certain range.
12 From Active Cell to Last Entry: This example illustrates the End property of the Range object in Excel VBA. We will use this property to select the range from the Active Cell to the last entry in a column.
13 Background Colors: Changing background colors in Excel VBA is easy. Use the Interior property to return an Interior object. Then use the ColorIndex property of the Interior object to set the background color of a cell.
14 Compare Ranges: Learn how to create a program in Excel VBA that compares randomly selected ranges and highlights cells that are unique.
15 Option Explicit: We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit forces you to declare all your variables.
16 Logical Operators: The three most used logical operators in Excel VBA are: And, Or and Not. As always, we will use easy examples to make things more clear.
17 Select Case: Instead of multiple If Then statements in Excel VBA, you can use the Select Case structure.
18 Mod Operator: The Mod operator in Excel VBA gives the remainder of a division.
19 Delete Blank Cells: In this example, we will create a VBA macro that deletes blank cells. First, we declare two variables of type Integer.
20 Loop through Defined Range: Use Excel VBA to loop through a defined range. For example, when we want to square the numbers in the range A1:A3.
21 Do Until Loop: VBA code placed between Do Until and Loop will be repeated until the part after Do Until is true.
22 Sort Numbers: In this example, we will create a VBA macro that sorts numbers. First, we declare three variables of type Integer and one Range object.
23 Remove Duplicates: Use Excel VBA to remove duplicates. In column A we have 10 numbers. We want to remove the duplicates from these numbers and place the unique numbers in column B.
24 Debugging: This example teaches you how to debug code in Excel VBA.
25 Error Handling: Use Excel VBA to create two programs. One program simply ignores errors. The other program continues execution at a specified line upon hitting an error.
26 Subscript Out of Range: The ‘subscript out of range’ error in Excel VBA occurs when you refer to a nonexistent collection member or a nonexistent array element.
27 Separate Strings: Let’s create a program in Excel VBA that separates strings. Place a command button on your worksheet and add the following code lines.
28 Instr: Use Instr in Excel VBA to find the position of a substring in a string. The Instr function is quite versatile.
29 Compare Dates and Times: This example teaches you how to compare dates and times in Excel VBA.
30 DateDiff Function: The DateDiff function in Excel VBA can be used to get the number of days, weeks, months or years between two dates.
31 Highlight Active Cell: Learn how to create a program in Excel VBA that highlights the row and column of the Active Cell (selected cell). This program will amaze and impress your boss.
32 Dynamic Array: If the size of your array increases and you don’t want to fix the size of the array, you can use the ReDim keyword. Excel VBA then changes the size of the array automatically.
33 User Defined Function: Excel has a large collection of functions. In most situations, those functions are sufficient to get the job done. If not, you can use Excel VBA to create your own function.
34 Read Data from Text File: Use Excel VBA to read data from a text file. This file contains some geographical coordinates we want to import into Excel.
35 Vlookup: Use the WorksheetFunction property in Excel VBA to access the VLOOKUP function. All you need is a single code line.
36 List Box: Use Excel VBA to place a list box on your worksheet. A list box is a list from where a user can select an item.
37 Check Box: A check box is a field which can be checked to store information. To create a check box in Excel VBA, execute the following steps.
38 Loan Calculator: This page teaches you how to create a simple loan calculator in Excel VBA. The worksheet contains the following ActiveX controls: two scrollbars and two option buttons.
39 Currency Converter: Use Excel VBA to create a Userform that converts any amount from one currency into another.
40 Progress Indicator: Learn how to create a progress indicator in Excel VBA. We’ve kept the progress indicator as simple as possible, yet it looks professional. Are you ready?
Check out all 300 examples.
Welcome to part one of the Ultimate VBA Tutorial for beginners.
If you are brand new to VBA, then make sure that you have read the post How To Create a Macro From Scratch in Excel so that your environment is set up correctly to run macros.
In this Excel VBA tutorial you will learn how to create real-world macros. The focus is on learning by doing. This tutorial has coding examples and activities to help you on your way. You will find a quiz at the end of this VBA tutorial. You can use this to test your knowledge and see how much you have learned.
In part one of this VBA tutorial we will concentrate on the basics of creating Excel macros. See the next sections for the learning outcomes and for tips on getting started with VBA.
“The noblest pleasure is the joy of understanding.” – Leonardo da Vinci
Learning Outcomes for this VBA Tutorial
When you finish this VBA tutorial you will be able to:
- Create a module
- Create a sub
- Understand the difference between a module and sub
- Run the code in a sub
- Write a value to a cell
- Copy the value from one cell to another
- Copy values from one range of cells to another
- Copy values between difference worksheets
- Test your output using the Immediate Window
- Write code faster using the With Statement
- Create and use variables
- Copy from a cell to a variable and vice versa
Before we get started, let’s look at some simple tips that will help you on your journey.
The Six Killer Tips For This VBA Tutorial
- Practice, Practice, Practice – Don’t try to learn by reading. Try the examples and activities.
- Type the code examples instead of copying and pasting – this will help you understand the code better.
- Have a clearly defined target for learning VBA. One you will know when you reach.
- Don’t be put off by errors. They help you write proper code.
- Start by creating simple macros for your work. Then create more complex ones as you get better.
- Don’t be afraid to work through each tutorial more than once.The more times you do it the more deeply embedded the knowledge will become.
Basic Terms Used in this VBA Tutorial
Excel Macros: A macro is a group of programming instructions we use to create automated tasks.
VBA: VBA is the programming language we use to create macros. It is short for Visual Basic for Applications.
Line of code: This a VBA instruction. Generally speaking, they perform one task.
Sub: A sub is made up of one or more lines of code. When we “Run” the sub, VBA goes through all the lines of code and carries out the appropriate actions. A macro and a sub are essentially the same thing.
Module: A module is simply a container for our subs. A module contains subs which in turn contain lines of code. There is no limit(within reason) to the number of modules in a workbook or the number of subs in a module.
VBA Editor: This is where we write our code. Pressing Alt + F11 switches between Excel and the Visual Basic Editor. If the Visual Basic editor is not currently open then pressing Alt + F11 will automatically open it.
The screenshot below shows the main parts of the Visual Basic Editor:
The Visual Basic Editor
Tip for the VBA Tutorial Activities
When you are working on the activities in this VBA Tutorial it is a good idea to close all other Excel workbooks.
Creating a Module
In Excel, we use the VBA language to create macros. VBA stands for Visual Basic for Applications.
When we use the term Excel Macros we are referring to VBA. The term macro is essentially another name for a sub. Any time you see the terms Excel Macros or VBA just remember they are referring to the same thing.
In VBA we create lines of instructions for VBA to process. We place the lines of code in a sub. These subs are stored in modules.
We can place our subs in the module of the worksheet. However, we generally only place code for worksheet events here.
In VBA, we create new modules to hold most of our subs. So for our first activity let’s go ahead and create a new module.
Activity 1
- Open a new blank workbook in Excel.
- Open the Visual Basic Editor(Alt + F11).
- Go to the Project – VBAProject window on the left(Ctrl + R if it is not visible).
- Right-click on the workbook and click Insert and then Module.
- Click on Module1 in the Project – VBAProject window.
- In the Properties window in the bottom left(F4 if not visible), change the module name from module1 to MyFirstModule.
End of Activity 1
The module is where you place your code. It is simply a container for code and you don’t use it for anything else.
You can think of a module like a section in a bookshop. It’s sole purpose is to store books and having similar books in a particular section makes the overall shop more organised.
The main window(or code window) is where the code is written. To view the code for any module including the worksheets you can double-click on the item in the Project – VBAProject window.
Let’s do this now so you can become familiar with the code window.
Activity 2
- Open a new workbook and create a new module like you did in the last activity.
- Double-click on the new module in the Project – VBAProject window.
- The code window for this module will open. You will see the name in the title bar of Visual Basic.
End of Activity 2
You can have as many modules as you like in a workbook and as many subs as you like within a module. It’s up to you how you want to name the modules and how you organize your subs within your modules.
In the next part of this VBA Tutorial, we are going to look at using subs.
How to Use Subs
A line of code is the instruction(s) we give to VBA. We group the lines of code into a sub. We place these subs in a module.
We create a sub so that VBA will process the instructions we give it. To do this we get VBA to Run the sub. When we select Run Sub from the menu, VBA will go through the lines of code in the sub and process them one at a time in the order they have been placed.
Let’s go ahead and create a sub. Then afterward, we will have a look at the lines of code and what they do.
Activity 3
- Take the module you created in the last activity or create a new one.
- Select the module by double-clicking on it in the Project – VBAProject window. Make sure the name is visible in the title bar.
- Enter the following line in the code window and press enter.
Sub WriteValue
- VBA will automatically add the second line End Sub. We place our code between these two lines.
- Between these two lines enter the line
Sheet1.Range("A1") = 5
You have created a sub! Let’s take it for a test drive.
- Click in the sub to ensure the cursor is placed there. Select Run->Run Sub/Userform from the menu(or press F5).
Note: If you don’t place the cursor in the sub, VBA will display a list of available subs to run. - Open Excel(Alt + F11). You will see the value 5 in the cell A1.
- Add each of the following lines to your sub, run the sub and check the results.
Sheet1.Range("B1") = "Some text" Sheet1.Range("C3:E5") = 5.55 Sheet1.Range("F1") = Now
You should see “Some text” in cells B1, 5.55 in the cells C3 to E5 and the current time and date in the cell F1.
End of Activity 3
Writing values to cells
Let’s look at the line of code we used in the previous section of this VBA Tutorial
Sheet1.Range("A1") = 5
We can also write this line like this
Sheet1.Range("A1").Value = 5
However in most cases we don’t need to use Value as this is the default property.
We use lines of code like these to assign(.i.e. copy) values between cells and variables.
VBA evaluates the right of the equals sign and places the result in the variable/cell/range that is to the left of the equals.
The line is saying “the left cellvariablerange will now be equal to the result of the item on the right”.
Let’s look the part of the code to the left of the equals sign
Sheet1.Range("A1") = 5
In this code , Sheet1 refers to the code name of the worksheet. We can only use the code name to reference worksheets in the workbook containing the code. We will look at this in the section The code name of the worksheet.
When we have the reference to a worksheet we can use the Range property of the worksheet to write to a range of one or more cells.
Using a line like this we can copy a value from one cell to another.
Here are some more examples:
' https://excelmacromastery.com/ Sub CopyValues() ' copies the value from C2 to A1 Sheet1.Range("A1") = Sheet1.Range("C2") ' copies the value from D6 to A2 Sheet1.Range("A2") = Sheet1.Range("D6") ' copies the value from B1 on sheet2 to A3 on sheet1 Sheet1.Range("A3") = Sheet2.Range("B1") ' writes result of D1 + D2 to A4 Sheet1.Range("A4") = Sheet2.Range("D1") + Sheet2.Range("D2") End Sub
Now it’s your turn to try some examples. Copying between cells is a fundamental part of Excel VBA, so understanding this will really help you on your path to VBA mastery.
Activity 4
-
-
- Create a new Excel workbook.
- Manually add values to the cells in sheet1 as follows: 20 to C1 and 80 to C2.
- Create a new sub called Act4.
- Write code to place the value from C1 in cell A1.
- Write code to place the result of C2 + 50 in cell A2.
- Write code to multiply the values in cells C1 and C2. Place the results in cell A3.
- Run the code. Cells should have the values A1 20, A2 130 and A3 1600
-
End of Activity 4
Cells in Different Sheets
We can easily copy between cells on different worksheets. It is very similar to how we copy cells on the same worksheet. The only difference is the worksheet names which we use in our code.
In the next VBA Tutorial activity, we are going to write between cells on different worksheets.
Activity 5
-
-
- Add a new worksheet to the workbook from the last activity. You should now have two worksheets called which are called Sheet1 and Sheet2.
- Create a new sub called Act5.
- Add code to copy the value from C1 on Sheet1 to cell A1 on Sheet2.
- Add code to place the result from C1 + C2 on Sheet1 to cell A2 on Sheet2.
- Add code to place the result from C1 * C2 on Sheet1 to cell A3 on Sheet2.
- Run the code in the sub(F5). Cells on Sheet2 should have the values as follows:
A1 20, A2 100 and A3 1600
-
End of Activity 5
The Code Name of the Worksheet
In the activities so far, we have been using the default names of the worksheet such as Sheet1 and Sheet2. It is considered good practice to give these sheets more meaningful names.
We do this by changing the code name of the worksheet. Let’s look at the code name and what it is.
When you look in the Project – VBAProject window for a new workbook you will see Sheet1 both inside and outside of parenthesis:
-
-
- Sheet1 on the left is the code name of the worksheet.
- Sheet1 on the right(in parenthesis) is the worksheet name. This is the name you see on the tab in Excel.
-
The code name has the following attributes
-
-
- We can use it to directly reference the worksheet as we have been doing e.g.
-
Sheet1.Range("A1")
Note: We can only use the code name if the worksheet is in the same workbook as our code.
-
-
- If the worksheet name is changed our code will still work if we are using the code name to refer to the sheet.
-
The worksheet name has the following attributes
-
-
- To reference the worksheet using the worksheet name we need to use the worksheets collection of the workbook. e.g.
-
ThisWorkbook.Worksheets("Sheet1").Range("A1")
-
-
- If the worksheet name changes then we need to change the name in our code. For example, if we changed the name of our sheet from Sheet1 to Data then we would need to change the above code as follows
-
ThisWorkbook.Worksheets("Data").Range("A1")
We can only change the code name in the Properties window.
We can change the worksheet name from both the worksheet tab in Excel and from the Properties window.
In the next activity, we will change the code name of the worksheet.
Activity 6
-
-
- Open a new blank workbook and go to the Visual Basic editor.
- Click on Sheet1 in the Project – VBAProject Window(Ctrl + R if not visible).
- Go to the Properties window(F4 if not visible).
- Change the code name of the worksheet to shReport.
- Create a new module and call it modAct6.
- Add the following sub and run it(F5)
-
Sub UseCodename() shReport.Range("A1") = 66 End Sub
-
-
- Then add the following sub and run it(F5)
-
Sub UseWorksheetname() ThisWorkbook.Worksheets("Sheet1").Range("B2") = 55 End Sub
-
-
- Cell A1 should now have the value 66 and cell B2 should have the value 55.
- Change the name of the worksheet in Excel to Report i.e. right-click on the worksheet tab and rename.
- Delete the contents of the cells and run the UseCodename code again. The code should still run correctly.
- Run the UseWorksheetname sub again. You will get the error “Subscript out of Range”. This cryptically sounding error simply means that there is no worksheet called Sheet1 in the worksheets collection.
- Change the code as follows and run it again. The code will now run correctly.
-
Sub UseWorksheetname() ThisWorkbook.Worksheets("Report").Range("B2") = 55 End Sub
The With keyword
You may have noticed in this VBA Tutorial that we need to use the worksheet name repeatedly – each time we refer to a range in our code.
Imagine there was a simpler way of writing the code. Where we could just mention the worksheet name once and VBA would apply to any range we used after that. The good news is we can do exactly that using the With statement.
In VBA we can take any item before a full stop and use the With statement on it. Let’s rewrite some code using the With statement.
The following code is pretty similar to what we have been using so far in this VBA Tutorial:
' https://excelmacromastery.com/ Sub WriteValues() Sheet1.Range("A1") = Sheet1.Range("C1") Sheet1.Range("A2") = Sheet1.Range("C2") + 50 Sheet1.Range("A3") = Sheet1.Range("C1") * Sheet1.Range("C2") End Sub
Let’s update this code using the With statement:
' https://excelmacromastery.com/ Sub UsingWith() With Sheet1 .Range("A1") = .Range("C1") .Range("A2") = .Range("C2") + 50 .Range("A3") = .Range("C1") * .Range("C2") End With End Sub
We use With and the worksheet to start the section. Anywhere VBA finds a full stop it knows to use the worksheet before it.
We can use the With statement with other types of objects in VBA including workbooks, ranges, charts and so on.
We signify the end of the With section by using the line End With.
Indenting(Tabbing) the Code
You will notice that the lines of code between the start and end With statments are tabbed once to right. We call this indenting the code.
We always indent the code between VBA sections that have a starting line and end line. Examples of these are as subs, the With statement, the If statement and the For loop.
You can tab the lines of code to the right by selecting the appropriate lines of code and pressing the Tab key. Pressing Shift and Tab will tab to the left.
Tabbing(or indenting) is useful because it makes our code more readable.
Activity 7
-
-
- Rewrite the following code using the With statement. Don’t forget to indent the code.
-
' https://excelmacromastery.com/ Sub UseWith() Sheet1.Range("A1") = Sheet1.Range("B3") * 6 Sheet1.Cells(2, 1) = Sheet1.Range("C2") + 50 Sheet1.Range("A3") = Sheet2.Range("C3") End Sub
End of Activity 7
Copying values between multiple cells
You can copy the values from one range of cells to another range of cells as follows
Sheet2.Range("A1:D4") = Sheet2.Range("G2:I5").Value
It is very important to notice than we use the Value property of the source range. If we leave this out it will write blank values to our destination range.
' the source cells will end up blank because Value is missing Sheet2.Range("A1:D4") = Sheet2.Range("G2:I5")
The code above is a very efficient way to copy values between cells. When people are new to VBA they often think they need to use some form of select, copy and paste to copy cell values. However these are slow, cumbersome and unnecessary.
It is important that both the destination and source ranges are the same size.
-
-
- If the destination range is smaller then only cell in the range will be filled. This is different to copy/pasting where we only need to specify the first destination cell and Excel will fill in the rest.
- If the destination range is larger the extra cells will be filled with #N/A.
-
Activity 8
-
-
- Create a new blank workbook in Excel.
- Add a new worksheet to this workbook so there are two sheets – Sheet1 and Sheet2.
- Add the following data to the range C2:E4 on Sheet1
-
-
-
- Write code to copy the data from Sheet1 to the range B3:D5 on Sheet2.
- Run the code(F5).
- Clear the results and then change the destination range to be smaller than the source range. Run again and check the results.
- Clear the results and then change the destination range to be larger than the source range. Run again and check the results.
-
End of Activity 8
Transposing a Range of Cells
If you need to transpose the date(convert from row to column and vice versa) you can use the WorksheetFunction Transpose.
Place the values 1 to 4 in the cells A1 to A4. The following code will write the values to E1 to H1
Sheet1.Range("E1:H1") = WorksheetFunction.Transpose(Sheet1.Range("A1:A4").Value)
The following code will read from E1:H1 to L1:L4
Sheet1.Range("L1:L4") = WorksheetFunction.Transpose(Sheet1.Range("E1:H1").Value)
You will notice that these lines are long. We can split one line over multiple lines by using the underscore(_) e.g.
Sheet1.Range("E1:H1") = _ WorksheetFunction.Transpose(Sheet1.Range("A1:A4").Value)
Sheet1.Range("L1:L4") = _ WorksheetFunction.Transpose(Sheet1.Range("E1:H1").Value)
How to Use Variables
So far in this VBA Tutorial we haven’t used variables. Variables are an essential part of every programming language.
So what are they and why do you need them?
Variables are like cells in memory. We use them to store temporary values while our code is running.
We do three things with variables
-
-
- Declare(i.e. Create) the variable.
- Store a value in the variable.
- Read the value stored in the variable.
-
The variables types we use are the same as the data types we use in Excel.
The table below shows the common variables. There are other types but you will rarely use them. In fact you will probably use Long and String for 90% of your variables.
Type | Details |
---|---|
Boolean | Can be true or false only |
Currency | same as decimal but with 4 decimal places only |
Date | Use for date/time |
Double | Use for decimals |
Long | Use for integers |
String | Use for text |
Variant | VBA will decide the type at runtime |
Declaring Variables
Before we use variables we should create them. If we don’t then we can run into various problems.
By default, VBA doesn’t make you declare variables. However, we should turn this behaviour on as it will save us a lot of pain in the long run.
To turn on “Require Variable Declaration” we add the following line to the top of our module
Option Explicit
To get VBA to automatically add this line, select Tools->Options from the menu and check Require Variable Declaration. Anytime you create a new module, VBA will add this line to the top.
Declaring a variable is simple. We use the format as follows
Dim variable_name As Type
We can use anything we like as the variable name. The type is one of the types from the table above. Here are some examples of declarations
Dim Total As Long Dim Point As Double Dim Price As Currency Dim StartDate As Date Dim CustomerName As String Dim IsExpired As Boolean Dim Item As Variant
To place a value in a variable we use the same type of statement we previously used to place a value in a cell. This is the statement with the equals sign:
' https://excelmacromastery.com/ Sub DeclaringVars() Dim Total As Long Total = 1 Dim Price As Currency Price = 29.99 Dim StartDate As Date StartDate = #1/21/2018# Dim CustomerName As String CustomerName = "John Smith" End Sub
Activity 9
-
-
- Create a new sub and call it UsingVariables.
- Declare a variable for storing a count and set the value to 5.
- Declare a variable for storing the ticket price and set the value to 99.99.
- Declare a variable for storing a country and set the value to “Spain”.
- Declare a variable for storing the end date and set the value to 21st March 2020.
- Declare a variable for storing if something is completed. Set the value to False.
-
End of Activity 9
The Immediate Window
VBA has a real nifty tool that allows us to check our output. This tool is the Immediate Window. By using the Debug.Print we can write values, text and results of calculations to the Immediate Window.
To view this window you can select View->Immediate Window from the menu or press Ctrl + G.
The values will be written even if the Immediate Window is not visible.
We can use the Immediate Window to write out our variables so as to check the values they contain.
If we update the code from the last activity we can write out the values of each variable. Run the code below and check the result in the Immediate Window(Ctrl + G if not visible).
' https://excelmacromastery.com/ Sub WritingToImmediate() Dim count As Long count = 5 Debug.Print count Dim ticketprice As Currency ticketprice = 99.99 Debug.Print ticketprice Dim country As String country = "Spain" Debug.Print country Dim enddate As Date enddate = #3/21/2020# Debug.Print enddate Dim iscompleted As Boolean iscompleted = False Debug.Print iscompleted End Sub
The Immediate is very useful for testing output before we write it to worksheets. We will be using it a lot in these tutorials.
Writing between variables and cells
We can write and read values between cells and cells, cells and variables,and variables and variables using the assignment line we have seen already.
Here are some examples
' https://excelmacromastery.com/ Sub VariablesCells() Dim price1 As Currency, price2 As Currency ' place value from A1 to price1 price1 = Sheet1.Range("A1") ' place value from price1 to price2 price2 = price1 ' place value from price2 to cell b2 Sheet1.Range("B2") = price2 ' Print values to Immediate window Debug.Print "Price 1 is " & price1 Debug.Print "Price 2 is " & price2 End Sub
Activity 10
-
-
- Create a blank workbook and a worksheet so it has two worksheets: Sheet1 and Sheet2.
- Place the text “New York” in cell A1 on Sheet1. Place the number 49 in cell C1 on Sheet2.
- Create a sub that reads the values into variables from these cells.
- Add code to write the values to the Immediate window.
-
End of Activity 10
Type Mismatch Errors
You may be wondering what happens if you use an incorrect type. For example, what happens if you read the number 99.55 to a Long(integer) variable type.
What happens is that VBA does it best to convert the variable. So if we assign the number 99.55 to a Long type, VBA will convert it to an integer.
In the code below it will round the number to 100.
Dim i As Long i = 99.55
VBA will pretty much convert between any number types e.g.
' https://excelmacromastery.com/ Sub Conversion() Dim result As Long result = 26.77 result = "25" result = 24.55555 result = "24.55" Dim c As Currency c = 23 c = "23.334" result = 24.55 c = result End Sub
However, even VBA has it’s limit. The following code will result in Type Mismatch errors as VBA cannot convert the text to a number
' https://excelmacromastery.com/ Sub Conversion() Dim result As Long result = "26.77A" Dim c As Currency c = "a34" End Sub
Tip: The Type Mismatch error is often caused by a user accidentally placing text in a cell that should have numeric data.
Activity 11
-
-
- Declare a Double variable type called amount.
- Assign a value that causes a Type Mismatch error.
- Run the code and ensure the error occurs.
-
End of Activity 11
VBA Tutorial Assignment
We’ve covered a lot of stuff in this tutorial. So let’s put it all together in the following assignment
Tutorial One Assignment
I have created a simple workbook for this assignment. You can download it using the link below
Tutorial One Assignment Workbook
Open the assignment workbook. You will place your code here
-
-
- Create a module and call it Assignment1.
- Create a sub called Top5Report to write the data in all the columns from the top 5 countries to the Top 5 section in the Report worksheet. This is the range starting at B3 on the Report worksheet. Use the code name to refers to the worksheets.
- Create a sub call AreaReport to write all the areas size to the All the Areas section in the Report worksheet. This is the range H3:H30. Use the worksheet name to refer to the worksheets.
- Create a sub called ImmediateReport as follows, read the area and population from Russia to two variables. Print the population per square kilometre(pop/area) to the Immediate Window.
- Create a new worksheet and call it areas. Set the code name to be shAreas. Create a sub called RowsToCols that reads all the areas in D2:D11 from Countries worksheet and writes them to the range A1:J1 in the new worksheet Areas.
-
End of Tutorial Assignment
The following quiz is based on what we covered this tutorial.
VBA Tutorial One Quiz
1. What are the two main differences between the code name and the worksheet name?
2. What is the last line of a Sub?
3. What statement shortens our code by allowing us to write the object once but refer to it multiple times?
4. What does the following code do?
Sheet1.Range("D1") = result
5. What does the following code do?
Sheet1.Range("A1:C3") = Sheet2.Range("F1:H3")
6. What is the output from the following code?
Dim amount As Long amount = 7 Debug.Print (5 + 6) * amount
7. What is the output from the following code?
Dim amt1 As Long, amt2 As Long amt1 = "7.99" Debug.Print amt1 amt2 = "14a" Debug.Print amt2
8. If we have 1,2 and 3 in the cells A1,A2 and A3 respectively, what is the result of the following code?
Sheet1.Range("B1:B4") = Sheet1.Range("A1:A3").Value
9. What does the shortcut key Alt + F11 do?
10. In the following code we declare a variable but do not assign it a value. what is the output of the Debug.Print statement?
Dim amt As Long Debug.Print amt
Conclusion of the VBA Tutorial Part One
Congratulations on finishing tutorial one. If you have completed the activities and the quiz then you will have learned some important concepts that will stand to you as you work with VBA.
In the Tutorial 2, we are going to deal with ranges where the column or row may differ each time the application runs. In this tutorial, we will cover
-
-
- How to get the last row or column with data.
- The amazingly efficient CurrentRegion property.
- How to use flexbile rows and columns.
- When to use Range and when to use Cells.
- and much more…
-
.
Please note: that Tutorials 2 to 4 are available as part of the VBA Fundamentals course in the membership section.
What’s Next?
Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.