VBA Tutorial 1 - The Ultimate Guide for Beginners - Excel Macro
VBA Tutorial 1 - The Ultimate Guide for Beginners - Excel Macro
Webinars About
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.
Contents [hide]
1. Create a module
2. Create a sub
3. Understand the difference between a module and sub
4. Run the code in a sub
5. Write a value to a cell
6. Copy the value from one cell to another
7. Copy values from one range of cells to another
8. Copy values between difference worksheets
9. Test your output using the Immediate Window
10. Write code faster using the With Statement
11. Create and use variables
12. 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.
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
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
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
1. Open a new workbook and create a new module like you did in the last activity.
2. Double-click on the new module in the Project – VBAProject window.
3. 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.
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
1. Take the module you created in the last activity or create a new one.
2. Select the module by double-clicking on it in the Project – VBAProject window. Make
sure the name is visible in the title bar.
3. Enter the following line in the code window and press enter.
Sub WriteValue
4. VBA will automatically add the second line End Sub. We place our code between these
two lines.
5. Between these two lines enter the line
Sheet1.Range("A1") = 5
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.
Sheet1.Range("A1") = 5
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 cell\variable\range 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.
' https://excelmacromastery.com/
Sub CopyValues()
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
End of Activity 4
Activity 5
1. Add a new worksheet to the workbook from the last activity. You should now have two
worksheets called which are called Sheet1 and Sheet2.
2. Create a new sub called Act5.
3. Add code to copy the value from C1 on Sheet1 to cell A1 on Sheet2.
4. Add code to place the result from C1 + C2 on Sheet1 to cell A2 on Sheet2.
5. Add code to place the result from C1 * C2 on Sheet1 to cell A3 on Sheet2.
6. Run the code in the sub(F5). Cells on Sheet2 should have the values as follows:
A1 20, A2 100 and A3 1600
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.
1. 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.
1. If the worksheet name is changed our code will still work if we are using the code name
to refer to the sheet.
1. 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")
1. 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")
Activity 6
Sub UseCodename()
shReport.Range("A1") = 66
End Sub
1. Cell A1 should now have the value 66 and cell B2 should have the value 55.
2. Change the name of the worksheet in Excel to Report i.e. right-click on the worksheet tab
and rename.
3. Delete the contents of the cells and run the UseCodename code again. The code should
still run correctly.
4. 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.
5. 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
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
' 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.
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.
Activity 7
1. 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
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
1. Write code to copy the data from Sheet1 to the range B3:D5 on Sheet2.
2. Run the code(F5).
3. Clear the results and then change the destination range to be smaller than the source
range. Run again and check the results.
4. 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
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:
Sheet1.Range("L1:L4") = WorksheetFunction.Transpose(Sheet1.Range("E1:
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)
Variables are like cells in memory. We use them to store temporary values while our code
is running.
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
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.
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
' https://excelmacromastery.com/
Sub DeclaringVars()
End Sub
Activity 9
End of Activity 9
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()
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.
' https://excelmacromastery.com/
Sub VariablesCells()
End Sub
Activity 10
1. Create a blank workbook and a worksheet so it has two worksheets: Sheet1 and Sheet2.
2. Place the text “New York” in cell A1 on Sheet1. Place the number 49 in cell C1 on Sheet2.
3. Create a sub that reads the values into variables from these cells.
4. Add code to write the values to the Immediate window.
End of Activity 10
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.
Dim i As Long
i = 99.55
VBA will pretty much convert between any number types e.g.
' https://excelmacromastery.com/
Sub Conversion()
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()
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
1. Declare a Double variable type called amount.
2. Assign a value that causes a Type Mismatch error.
3. Run the code and ensure the error occurs.
End of Activity 11
Open the assignment workbook. You will place your code here
3. What statement shortens our code by allowing us to write the object once but refer to it
multiple times?
Sheet1.Range("D1") = result
Debug.Print (5 + 6) * amount
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
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?
Debug.Print amt
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
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.
161 Comments
← Older Comments
Verle Lloyd on July 3, 2020 at 5:16 pm
Please keep me on your e-mail list. I am very much interested in your
information, just busy, busy, busy… (COVID has added strain to business…)
Reply
Reply
Reply
Reply
Ashu Ashu A on March 10, 2022 at 11:54 am
I like your lessons on Excel VBA but your ebook is out of reach for
those of us in Africa
Thanks
Reply
You’re welcome.
Reply
nice
Reply
Excel Path on July 28, 2020 at 3:42 pm
Very Nice.. Looking forward to learn from this.
Reply
Reply
Hey,
Reply
Reply
Reply
Reply
Reply
Reply
Berend Kemper on May 11, 2021 at 9:07 pm
Thanks for showing such great tutorials! Back in 2019 your tutorials helped
me to gain confidence to figure out lots of stuff in VBA. Thanks to that
starting point i went into a different path and i am now writing code in
JavaScript and code in Node JS
Reply
Reply
Reply
Reply
Good day,
could you please advise me? I need to make a button to add and remove a
line. The row is inserted below the current row and vice versa.
Reply
Keep me on your email list, please. Thanks for your messages, and I am
asking for more.
Reply
Thanks!
Reply
Reply
John Phillis on March 10, 2022 at 5:12 pm
Please keep me on the list, I file everything you send for reference
Reply
My regards
Elias
Reply
Thanks Elias.
Reply
I have been tied up with other commitments but … please leave my name
on your list. I have found your material to be very helpful and easy to
understand.
Many thanks for material well presented.
Regards
Nigel
Reply
Reply
Pam Kornegay on September 9, 2022 at 3:13 am
Thanks for this website! I am enjoying learning with your easy to follow-
along method of instructing. The vba-tutorial-1 webpage makes reference
to the ExcelVBAHandbook, and indicates you learn how to build 10 Excel
VBA applications from scratch. What does the additional lesson cover?
Thanks.
Reply
Reply
Reply
Hi Jason,
Thanks for your question.
The Excel VBA Handbook course teaches how to create real-world
Excel VBA applications. This course is for you if you want acquire
the skills to build any Excel VBA applications, write better code,
reduce errors and create your applications 5 to 10 times faster then
this course can help.
-Paul
Reply
WRS on November 8, 2022 at 1:38 am
Hi Paul, Thank you for the great website. The articles are very well
organized. We have a new challenge as offices like mine are moving to MS
Office 365 (cloud). I’m told VBA is not supported there. But a Microsoft
version of javascript is their new automation language. There is a script-
check plug in for Excel, to help folks re-write their VBA code into javascript. I
havent tried it. I have thousands of lines of VBA code to consider! What do
you think doing an article about this situation? Regards, WRS
Reply
Reply
MANZI Ndamukunze on March 15, 2023 at 11:31 am
Thanks for this. can we have document pdf of this basic notion ?
Reply
trey mayes on January 16, 2023 at 10:56 pm
Reply
← Older Comments
Password:
Remember Me
Login
» Register
» Lost your Password?
Designed by Elegant Themes | Powered by WordPress