VBA Programming Fundamentals
VBA Programming Fundamentals
VBA Programming
Fundamentals
Table of Content
1. Introduction
2. VBA Fundamentals
3. VBA Language Elements and Comments
4. Variables, Data Types, and Constants
5. Assignment Statements
6. Object Variables
7. Built-in Functions
8. Manipulating Objects – With-End With
9. Manipulating Collections – For-Next
10. Controlling Code Execution
2
List of Practice
1. Practice 8.1
2. Practice 8.2
3. Practice 8.3
4. Practice 8.4
5. Practice 8.5
6. Practice 8.6
7. Practice 8.7
8. Practice 8.8
9. Practice 8.9
10. Practice 8.10
3
1. Introduction - VBA
4
1. Introduction – Code, Module and Procedures
▪ You perform actions in VBA by executing VBA code. You write (or
record) VBA code which is stored in a VBA module.
Sub Test()
Sum = 1 + 1
MsgBox "The answer is " & Sum
End Sub
6
1. Introduction - Sub and Function procedures
7
1. Introduction – VBE Components
▪ You view or edit a module by using Visual Basic Editor (VBE). To
see this hidden VBE environment, you need to activate it. The
quickest way to activate the VBE is to press Alt+F11 when Excel is
active. To return to Excel, press Alt+F11 again.
▪ You can also activate the VBE by using the Visual Basic command
on Excel’s Developer tab.
▪ Components of VBE:
▪ Menu bar: The VBE menu bar contains commands that you use
to do things with the various components in the VBE.
▪ Toolbar: The Standard toolbar is directly under the menu bar
by default. 8
1. Introduction – VBE Components
▪ Components of VBE:
▪ The project window displays a tree diagram that shows every
workbook currently open in Excel. If the Project window is not
visible, press Ctrl+R or use the View ➪ Project Explorer
command.
▪ A code window contains VBA code. To view an object’s Code
window, double-click the object in the Project window.
▪ The immediate window execute individual VBA statements. It
may or may not be visible. If it isn’t visible, press Ctrl+G or use
the View ➪ Immediate Window command.
9
1. Introduction – VBE Components
▪ Components of VBE:
▪ The locals window displays all of the declared variables in the
current procedure and their values. When the Locals window
is visible, it is automatically updated every time there is a
change of a variable. It is helpful to trace through each line of
code and steps into procedures. This allows you to view the
effect of each statement on variables.
10
1. Introduction – VBE
Components
11
1. Introduction – Immediate Window
▪ You can use the Immediate Window to test a line of code or to
display result of a line of code.
▪ To execute code in the Immediate window:
▪ Type a line of code in the Immediate window
▪ Press ENTER to execute the statement
▪ Enter the following line of code in the Immediate window display a
message.
Msgbox "Hello World!"
12
1. Introduction – Immediate Window
▪ If you want to run multiple lines of code, use colon : between them.
▪ Enter the following lines of code in the Immediate Window to
display 2 messages.
Msgbox "Hello World!": Msgbox "Welcome to the course"
▪ You can print the result of a line of code in the Immediate Window
by using Question mark ? or Print command.
▪ Enter the following line of code in the Immediate window returns
the result of the equation.
? 123*123
Print 123*123
13
1. Introduction – VBA Module
▪ A single VBA module can store any number of Sub procedures,
Function procedures.
▪ Follow these steps to add a new VBA module manually to a project:
▪ 1. Select the project’s name in the Project window.
▪ 2. Choose Insert ➪ Module.
▪ Or you can do the following:
▪ 1. Right-click the project’s name.
▪ 2. Choose Insert ➪ Module from the shortcut menu.
14
1. Introduction – VBA Module
15
1. Introduction – Getting VBA Code into a Module
▪ You can get VBA code into a VBA module in three ways.
▪ Copy the code from one module and paste it into another.
16
1. Introduction – Getting VBA Code into a Module
▪ Create your first VBA Code by type the following code into the
module.
Sub GuessName()
Dim Msg as String
Dim Ans As Long
Msg = "Is your name " & Application.UserName & "?"
Ans = MsgBox(Msg, vbYesNo)
If Ans = vbNo Then MsgBox "Oh, never mind."
If Ans = vbYes Then MsgBox "I knew it!"
End Sub
▪ Each object has its own set of attributes, which are called properties,
and its own set of actions, called methods.
19
2. VBA Fundamentals – Objects
20
2. VBA Fundamentals – Objects
▪ To view all the objects available in VBA, you can also go to the
website: https://learn.microsoft.com/en-
us/office/vba/api/overview/excel/object-model
Application.ThisWorkbook.Sheets("Sheet1").Range("A1").Select
21
2. VBA Fundamentals – Objects
▪ If you have your cursor already in cell A1, you can simply use the
ActiveCell object, negating the need to spell out the range:
Activecell.Select
22
2. VBA Fundamentals – Collections
23
2. VBA Fundamentals - Collections
Worksheets(1).Select
Worksheets("Mysheet").Select
▪ You can also use Sheets collection which is a collection of all the
sheets in the specified or active workbook.
24
2. VBA Fundamentals – Properties
▪ Some properties can be changed. For example, you can change the
name of your worksheet by changing its Name property:
Worksheets("Sheet1").Name = "MySheet"
▪ But some properties are read-only. You can’t assign a value to them
directly. For example, index property of a worksheet is read-only.
ActiveSheet.Index
25
2. VBA Fundamentals – Methods
Range("A1").Select Range("A1").Copy
▪ Some methods have arguments that can dictate how they are
applied. For instance, the Paste method can be used more effectively
by explicitly defining the Destination argument.
ActiveSheet.Paste Destination:=Range("B1")
26
2. VBA Fundamentals – Methods
▪ Properties:
▪ Methods:
27
2. VBA Fundamentals – Add Method
▪ How to create a new workseet using VBA?
▪ You can use Add method for Sheets object which has following
syntax:
Sheets. Add([Before],[After],[Count])
▪ Before, After: An object that specifies the sheet before which the
new sheet is added. The default if before.
▪ Count: The number of sheets to be added. The default value is the
number of selected sheets.
30
2. VBA Fundamentals – Working With Ranges
31
2. VBA Fundamentals – Range Property
▪ The example below puts the value 12.3 into cell A1 on Sheet1:
Worksheets("Sheet1").Range("A1").Value = 12.3
Worksheets("Sheet1").Range("Input").Value = 100
32
2. VBA Fundamentals – Range Property
33
2. VBA Fundamentals – Cells Property
▪ Another way to reference a range is to use the Cells property on
worksheet objects. Here the syntaxes:
Worksheets("Sheet1").Cells(1, 1) = 9
34
2. VBA Fundamentals – Cells Property
▪ The second syntax of the Cells property uses a single argument that
can range from 1 to 17,179,869,184. This number is equal to the
number of cells in an Excel worksheet. The cells are numbered
starting from A1 and continuing right and then down to the next
row. The 16,384th cell is XFD1; the 16,385th cell is A2 ➪ Do not
recommend to use.
▪ You can also use this syntax with a Range object. In this case, the
cell returned is relative to the Range object referenced.
▪ The third syntax for the Cells property simply returns all cells on the
referenced worksheet.
35
2. VBA Fundamentals – Practice
Practice 8.1. Use Immediate Window to:
1. Enter following data using different methods (Range and Cell
properties) into worksheet 1:
37
3. VBA Language Elements
▪ This is an example of a simple procedure, which is stored in a
VBA module, calculates the sum of the first 100 positive integers:
Sub VBA_Demo()
' This is a simple VBA Example
Dim Total As Long, i As Long
Total = 0
For i = 1 To 100
Total = Total + i
Next i
MsgBox Total
End Sub
38
3. VBA Language Elements
▪ Common VBA language elements, including the following:
▪ A comment (the line that begins with an apostrophe).
▪ A variable declaration statement (the line that begins with
Dim).
▪ Two variables (Total and i)
▪ Two assignment statements (Total = 0 and Total = Total + i)
▪ A looping structure (For - Next)
▪ A VBA function (MsgBox)
39
3. VBA Language Elements: Comment
▪ You can use a complete line for your comment, or you can insert a
comment after an instruction on the same line.
40
3. VBA Language Elements: Comment
Sub CommentDemo()
' This procedure does nothing of
value
x = 0 'x represents nothingness
' Display the result
MsgBox x
End Sub
41
3. VBA Language Elements: Comment
▪ VBA ignores any text that follows an apostrophe – except when
the apostrophe is contained within quotation marks – up until the
end of the line.
▪ The following are a few general tips on making the best use of
comments:
▪ Describe briefly the purpose of each procedure that you write.
▪ Describe the purpose of variables.
▪ Write comments while you code rather than afterward.
42
4. Variables, Data Types, and Constants – Variables
▪ VBA’s main purpose is to manipulate data. Some data resides in
objects, such as worksheet ranges. Other data is stored in
variables that you create.
▪ A variable is a named storage location used to store data during
the execution of a program.
▪ Few rules regarding variable names:
▪ The first character must be alphabetic.
▪ VBA doesn’t distinguish between case.
▪ You can’t use spaces or periods.
▪ You can’t embed special type declaration characters (#, $, %,
&, or !) in a variable name. 43
4. Variables, Data Types, and Constants – Variables
▪ You assign a value to a variable by using the equal sign “=“ operator.
▪ VBA has many reserved words, which are words that you can’t use
for variable or procedure names. For example: Next, For, With
▪ Examples of assignment expressions that use various types of
variables:
x = 1
InterestRate = 0.075
LoanPayoffAmount = 243089.87
DataEntered = False
x = x + 1
MyNum = YourNum * 1.25
UserName = "Bob Johnson"
DateStarted = #12/14/2012# 44
4. Variables, Data Types, and Constants – Data Types
▪ Data type refers to how data is stored in memory – as integers,
real numbers, strings, and so on.
▪ Although VBA can take care of data typing automatically, it does
so at a cost: slower execution and less efficient use of memory ➪
It is recommended to define the data type for variables used.
▪ When VBA works with data, execution speed is partially a
function of the number of bytes that VBA has at its disposal ➪
The fewer the bytes used by the data, the faster that VBA can
access and manipulate the data.
45
4. Variables, Data Types, and Constants – Declare Variables
▪ If you don’t declare the data type for a variable that you use in a
VBA routine, VBA uses the default data type, Variant. Data stored
as a Variant acts like a chameleon: it changes type, depending on
what you do with it.
▪ The following procedure demonstrates how a variable can
assume different data types:
Sub VariantDemo()
MyVar = True
MyVar = MyVar * 100
MyVar = MyVar / 4
MyVar = "Answer: " & MyVar
MsgBox MyVar
End Sub
46
4. Variables, Data Types, and Constants – Declare Variables
▪ You can use the VBA TypeName function to determine the data
type of a variable. Here’s a modified version of the VariantDemo
procedure. This version displays the data type of MyVar at each
step
Sub VariantDemo3()
MyVar = True
MsgBox TypeName(MyVar)
MyVar = MyVar * 100
MsgBox TypeName(MyVar)
MyVar = MyVar / 4
MsgBox TypeName(MyVar)
MyVar = "Answer: " & MyVar
MsgBox TypeName(MyVar)
MsgBox MyVar
End Sub 47
4. Variables, Data Types, and
Constants – Data Types
48
4. Variables, Data Types, and Constants – Data Types
49
4. Variables, Data Types, and Constants – Declare Variables
▪ To force yourself to declare all variables that you use, include the
following as the first instruction in your VBA module:
50
4. Variables, Data Types, and Constants – Constants
51
4. Variables, Data Types, and Constants – Scoping
52
4. Variables, Data Types, and Constants – Scoping
55
5. Assignment Statements
56
5. Assignment Statements
57
6. Object Variables
▪ To make your code more efficient, you can condense the routine
with an object variable.
Sub ObjVar()
Dim MyCell As Range
Set MyCell = Worksheets("Sheet1").Range("A1")
MyCell.Value = 124
MyCell.Font.Bold = True
MyCell.Font.Italic = True
MyCell.Font.Size = 14
MyCell.Font.Name = "Cambria"
End Sub
60
Practice
Practice 8.2. Write VBA sub procedures that perform the following
tasks:
1. Sub create_sheets to creates new worksheets after the worksheet 1,
where each worksheet's name corresponds to a customer's name in
worksheet 1. All customer’s worksheets should have the following
loan information.
61
Practice
Them Option Explicit: pha hien loi
Sub create_sheet()
Sheets.Add after:=Worksheets(1),
Count:=3
Sheets(2).name = Worksheets
name = "John"
loan_type = "Interest only"
amount = 10000
interest_rate = 0.1
num_years = 10
interest_payment = amount *
interest_rate 62
MsgBox interest_payment
End Sub
7. Built-in Functions
InputBox(prompt[, title])
65
7. Built-in Functions – Common Built-in Functions
66
7. Built-in Functions – Practice
Practice 8.3. Write sub procedure
inputbox to:
▪ Declare the suitable types of
variable for following data.
▪ Use inputbox built-in function
to ask the user to enter the data.
▪ Store the data entered by the
user to a new worksheet,
naming the worksheet after the
customer's name.
▪ Display the message: “Your annual interest is $800”
67
8. Manipulating Objects – With-End With
68
8. Manipulating Objects – With-End With
▪ You can rewrite this procedure using the With-End With construct.
The following procedure performs exactly like the preceding one:
Sub ChangeFont2()
With Selection.Font
.Name = "Cambria"
.Bold = True
.Italic = True
.Size = 12
.Underline = xlUnderlineStyleSingle
.ThemeColor = xlThemeColorAccent1
End With
End Sub
▪ A procedure that uses the With-End With construct to change
several properties of an object can be faster 70
8. Manipulating Objects – Practice
Practice 8.4. Write VBA sub change_format that performs following changes:
▪ Bold for range A1:A5 (Range.Font.Bold = True)
▪ Right allignment for range B1:B5 (Range.HorizontalAlignment =
xlRight)
▪ Solid border for range A1:B5 (Range.Borders.LineStyle =
xlContinuous)
▪ Currency format for the cells B3
(Range. NumberFormat =
“$#,##0.00”)
▪ Autofit for column A and B
(Column.AutoFit)
71
9. Manipulating Collections – For-Next
72
9. Manipulating Collections – For-Next
▪ The following procedure uses the For Each-Next construct with the
Worksheets collection in the active workbook. When you execute
the procedure, the MsgBox function displays each worksheet’s
Name property.
Sub CountSheets()
Dim Item as Worksheet
For Each Item In ActiveWorkbook.Worksheets
MsgBox Item.Name
Next Item
End Sub
73
9. Manipulating Collections – For-Next
▪ VBA provides a way to exit a For-Next loop before all the elements
in the collection are evaluated. Do this with an Exit For statement:
Sub SelectNegative()
Dim Cell As Range
For Each Cell In Range("1:1")
If Cell.Value < 0 Then
Cell.Select
Exit For
End If
Next Cell
End Sub
74
10. Controlling Code Execution
▪ VBA provides a way to exit a For-Next loop before all the elements
in the collection are evaluated. Do this with an Exit For statement:
▪ The preceding section describes the For Each-Next construct, which
is a type of loop.
▪ This section discusses the additional ways of controlling the
execution of your VBA procedures.
▪ If-Then constructs
▪ Select Case constructs
▪ For-Next loops
▪ Do While loops
▪ Do Until loops
75
10. Controlling Code Execution – If-Then Constructs
▪ The Else clause is optional. If included, the Else clause lets you
execute one or more instructions when the condition that you’re
testing isn’t True.
76
10. Controlling Code Execution – If-Then Constructs
Sub GreetMe1()
If Time < 0.5 Then MsgBox "Good Morning"
End Sub
77
10. Controlling Code Execution – If-Then Constructs
Sub GreetMe1a()
If Time < 0.5 Then
MsgBox "Good Morning"
End If
End Sub
78
10. Controlling Code Execution – If-Then Constructs
Sub GreetMe2()
If Time < 0.5 Then MsgBox "Good Morning"
If Time >= 0.5 Then MsgBox "Good Afternoon"
End Sub
Sub GreetMe3a()
If Time < 0.5 Then
MsgBox "Good Morning"
' Other statements go here
Else
MsgBox "Good Afternoon"
' Other statements go here
End If
End Sub
80
10. Controlling Code Execution – If-Then Constructs
Sub GreetMe4()
If Time < 0.5 Then MsgBox "Good Morning"
If Time >= 0.5 And Time < 0.75 Then MsgBox "Good Afternoon"
If Time >= 0.75 Then MsgBox "Good Evening"
End Sub
81
10. Controlling Code Execution – If-Then Constructs
82
10. Controlling Code Execution – If-Then Constructs
▪ Here’s how you can use this syntax to rewrite the GreetMe
procedure:
Sub GreetMe5()
If Time < 0.5 Then
MsgBox "Good Morning"
ElseIf Time >= 0.5 And Time < 0.75
Then
MsgBox "Good Afternoon"
Else
MsgBox "Good Evening"
End If
End Sub
83
10. Controlling Code Execution – If-Then Constructs – Practice
Practice 8.5. Write VBA sub discount with If – Then constructs that
asks the customer to enter the sales amount then returns the
corresponding discount rate. For example, if a customer enters 15, it
will display the message “The discount rate is 15%”
85
10. Controlling Code Execution– Select Case Constructs
Practice 8.6. Write VBA sub discount2 with Select Case constructs that
asks the customer to enter the sales amount then returns the
corresponding discount rate. For example, if a customer enters 15, it
will display the message “The discount rate is 15%”
88
10. Controlling Code Execution– For-Next Loops
89
10. Controlling Code Execution– For-Next Loops
▪ You can also use a Step value to skip some values in the loop. Here’s
the same procedure rewritten to sum the square roots of the odd
numbers between 1 and 100:
Sub SumOddSquareRoots()
Dim Sum As Double
Dim Count As Integer
Sum = 0
For Count = 1 To 100 Step 2
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub
90
10. Controlling Code Execution– For-Next – Practice
Practice 8.7. Write VBA sub create_sheets2 with For-Next loop
construct to create new worksheets, where each worksheet's name
corresponds to a customer's name:
▪ Hint: You can find the last row of column A using following
code: Cells(Rows.Count, 1).End(xlUp).Row
91
10. Controlling Code Execution – For-Next – Practice
Practice 8.8. Write VBA sub delete_sheets2 with For-Next loop
construct to delete all worksheets except the first worksheet:
92
10. Controlling Code Execution – Do While Loops
▪ The sub below finds the sum of the squares of the first n positive
integers, ensuring the sum does not exceed a specified threshold value.
Sub SumSquare()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do While sum_square + n ^ 2 <= threshold
sum_square = sum_square + n ^ 2
n = n + 1
Loop
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub
94
10. Controlling Code Execution– Do While Loops
95
10. Controlling Code Execution– Do While Loops
▪ The following procedure has the same result as the Sumsquare
procedure, but it uses the second Do While Loop syntax, which
checks the condition at the end of the loop.
Sub SumSquare2()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do
sum_square = sum_square + n ^ 2
n = n + 1
Loop While sum_square + n ^ 2 <= threshold
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub 96
10. Controlling Code Execution – Do While Loops – Practice
97
10. Controlling Code Execution– Do Until Loops
98
10. Controlling Code Execution– Do Until Loops
99
10. Controlling Code Execution– Do Until Loops
▪ The examples that follow perform the same action as the Do While
date entry example in the previous sectiom. For this syntax, the
condition is evaluated at the beginning of the loop.
Sub SumSquare3()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do Until sum_square + n ^ 2 > threshold
sum_square = sum_square + n ^ 2
n = n + 1
Loop
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub 100
10. Controlling Code Execution– Do Until Loops
▪ The examples that follow perform the same action as the Do While
date entry example in the previous section. For this syntax, the
condition is evaluated at the end of the loop.
Sub SumSquare4()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do
sum_square = sum_square + n ^ 2
n = n + 1
Loop Until sum_square + n ^ 2 > threshold
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub 101
10. Controlling Code Execution– Do Until Loops – Practice
Practice 8.10. Write VBA sub years_to_target2 with Do Until Loop that
asks the user to enter the amount of money he has, the annual interest
rate, the amount of money he wants in the future. After that, the sub
should return the number of years needed to achieve that target. For
example, if he has $100,000, the interest rate is 10%, and he wants
$200,000 in the future, the sub should return “You need 8 years to
achieve the target, and you will have $214,000”
102