Excelvba365me Preview
Excelvba365me Preview
Excelvba365me Preview
by
Excel VBA 365 Made Easy is an independent publication and is not affiliated with, nor has it been
authorized, sponsored, or otherwise approved by Microsoft Corporation.
Trademarks
Microsoft, Visual Basic, Excel and Windows are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries.
Liability
The purpose of this book is to provide basic guidelines for people interested in Excel VBA 365
programming. Although every effort and care has been taken to make the information as accurate as
possible, the author shall not be liable for any error, harm or damage arising from using the
instructions given in this book.
Copyright© Liew Voon Kiong 2020. All rights reserved. No part of this book may be reproduced or
transmitted in any form or by any means, without permission in writing from the author.
Acknowledgement
I would like to express my sincere gratitude to many people who have made their contributions in
one way or another to the successful publication of this book.
My special thanks go to my children Xiang, Yi and Xun. My daughter Xiang edited this book while my
sons Yi and Xun contributed their ideas and even wrote some of the sample programs for this book.
I would also like to appreciate the support provided by my beloved wife Kim Huang and my youngest
daughter Yuan. I would also like to thank the millions of visitors to my Excel VBA Tutorial website at
https://excelvbatutor.com/ for their support and encouragement.
Dr. Liew Voon Kiong holds a bachelor’s degree in Mathematics, a master’s degree in Management
and a doctorate in Business Administration. He has been involved in Visual Basic programming for
more than 30 years. He created the popular online Visual Basic Tutorial at www.vbtutor.net which
has attracted millions of visitors since 1996. It has consistently been one of the highest ranked
Visual Basic websites.
Dr. Liew is also the author of the Visual Basic Made Easy series, which includes Excel VBA Made
Easy, Visual Basic 6 Made Easy, Visual Basic 2008 Made Easy, Visual Basic 2010 Made Easy,
Visual Basic 2013 Made Easy, Visual Basic 2015 Made Easy, Visual Basic 2017 Made Easy and
Visual Basic 2019 Made Easy . Besides the VB books, he has also published JavaScript Made
Easy, JavaScript & JQuery Made Easy and HTML & CSS Made Easy. Dr. Liew’s books have
been used in high school and university computer science courses all over the world.
TABLE OF CONTENTS
1.2.2 Building Excel VBA 365 using the Visual Basic Editor 25
Example 1.6 A Macro that Populates Cells using the For…Next Loop 40
Example 1.7 A Macro that Populates the Cells with Characters using the Chr() Function.
41
2.5 Arrays 60
Example 3.2 Separating the Message into Three Lines using the Chr() Function 70
Chapter 5 Looping 85
Example 10.14 Search for a Specific Value and Replace with New Value 156
Example 11.8 Adding Items to a List Box using the AddItem Method 169
Example 12.2 Creating the Formula to Calculate the Area of a Triangle 181
Example 13.2 Changing the Font Size Based on the User's Input 194
Example 15.1 Using Several Time and Date Formatting Functions 204
Example 22.3 Dialog to Let the User to Continue or Stop Printing 294
Index 400
Chapter 1 Introduction to Excel VBA 365
This book is based on the latest Microsoft Excel, which is one of the apps of Microsoft Office 365;
hence I named this book Excel VBA 365 Made Easy. All the Excel VBA code examples in this book
have been tested in Microsoft Excel 365 and proven to be bugs free, therefore you may try them out
in your own settings. Although the examples are based on MS Excel 365, they should be workable in
older versions of MS Excel because the syntaxes are based largely on Visual Basic 6.
VBA stands for Visual Basic for Applications. It is an event-driven programming language Visual
Basic embedded inside Microsoft Office applications like Microsoft Excel, Microsoft Word, Microsoft
PowerPoint and more. By running Visual Basic within the Microsoft Office applications, we can build
customized functions and macros to enhance the capabilities of those applications. Besides that, we
can build VBA macros that automates processes in the Microsoft Office applications.
Among the Visual Basic applications, Microsoft Excel VBA 365 is the most popular. There are many
reasons why we should learn VBA for Microsoft Excel, one of the reasons is you can understand the
fundamentals of Visual Basic programming within the MS Excel environment, without having to
purchase a copy of Microsoft Visual Basic software. Another reason is by learning Excel VBA; you
can build custom-made functions to complement the built-in formulas and functions of Microsoft
Excel.
Although MS Excel has numerous built-in formulas and functions, it is still insufficient to cater for
many complex calculations and applications. This book was written in such a way that you can learn
VBA for MS Excel from scratch, and everyone shall be able to master it in a short time! Basically,
Excel VBA code is created using Visual Basic, therefore, its syntaxes remain largely the same for
every version of Microsoft Excel. Although this book is based on MS Excel 365, you may apply it in
older versions of MS Excel.
1.2 The Visual Basic Editor in MS Excel 365
To create VBA applications in Microsoft Excel 365, you must own a copy of Microsoft office 365 that
comes with the basic package comprising Microsoft Word, Microsoft PowerPoints, Microsoft Excel,
Microsoft Access and more. If you have already owned a copy of Microsoft Office 365, proceed to
program Excel VBA by launching Microsoft Excel 365. Figure 1.1 shows the initial Workbook of
Microsoft Excel 365.
Next, click on the Developer tab to access the Developer window, the environment for building Excel
365 Visual Basic applications. In the Developer environment, you may play with all kinds of tools and
apps that you can use to develop VBA and macros.
There are three ways to start programming Excel VBA, by placing controls on the worksheet and
double click it to enter the Visual Basic Editor. The second way is to enter the Visual Basic Editor
directly by clicking the View Code button or the Visual Basic button in the Developer environment. In
addition, you can also program VBA by creating macros.
1.2.1 Building Excel VBA 365 using the Controls.
There are two categories of controls, Form controls and ActiveX controls. Form controls are built into
Excel whereas ActiveX controls are loaded separately. Though Form controls are simpler to
use, ActiveX controls allow for more flexible design.
To use the controls, navigate to the Developer tab then click on the Insert button to access the
ActiveX controls and Form Controls, as shown in Figure 1.2.
Let us start with the command button. To place a command button on the MS Excel worksheet, click
on the command button under ActiveX controls and draw it on the worksheet, as shown in Figure
1.3. Notice that the Developer environment is in the Design Mode at this stage.
Figure 1.3 The Command Button in the Design Mode
At this stage, you might want to customize the command button by changing some of its properties.
To access the properties, right-click the command button and select the Properties option to launch
the Properties window, as show in Figure 1.4.
Figure 1.4 The Properties Window
You may change its name to any name you wish but for learning purposes I suggest you change its
name to Cmd_ShowMsg and its Caption to Show Message, as shown in Figure 1.5.
Notice that the caption on the command button has changed to Show Message.
Figure 1.5
Next, click on the command button to enter the Visual Basic Editor (We will use the short form VBE
every now and then in the book). In the VBE, Enter the statements as shown in Example 1.1, as
follows:
To run the VBA program, quit the VBE and the Design Mode and then click on the command
button. A message box will appear, as shown in Figure 1.7
Figure 1.7
The next example involved the use of the Range object and its property Value, as well as the cells
object. The program also introduces a For...Next loop which you are already familiar if you
have been programming in Visual Basic 6.
The first statement will populate the cells from the range cell A1 to cell D4 with the phrase "Excel
VBA 365''. The second statement populates the cells from the range cell A5 to cell D5 with the value
of 100. The third statement populates the cells from the range cell A6 to cell D6 with the value of 50.
The For…Loop statement adds the corresponding values of row 5 and row 6 and display them in
row 7. Running the VBA produces the output UI as shown in Figure 1.8.
Figure 1.8
1.2.2 Building Excel VBA 365 using the Visual Basic Editor
To access Visual Basic Editor directly, click on Visual Basic or View Code in the Developer
environment. In the VBE, you are presented with two items, General and Worksheet. General is the
declaration section when you can declare some global variables. Worksheet is the object where you
can write some VBA code to interact with it. The current active worksheet is sheet1(the name
assigned to Worksheet1) as only one worksheet is available, as seen on the right section of the
VBE, as shown in Figure 1.9.
If you add another worksheet to the workbook, the VBE will shows two worksheets, sheet1 and
sheet2, as shown in Figure 1.10
Figure 1.10
When you click the Worksheet, an event procedure will appear, as shown below:
A worksheet has many events associated with it (for that matter any Excel VBA objects has events
associated with them). The default event is SelectionChange , as shown in the event procedure
above. To view more events associated with the WorkSheet, click on the small inverted triangle on
the top right corner of VBE, you will see a drop-down list of events, as shown in Figure 1.11.
Figure 1.11 The Worksheet Events
Now let us enter some code into the event procedure, as follows:
This code means whenever you click on another cell of the Worksheet, the message " You have
changed your selection" message will appear, as shown in Figure 1.12.
Figure 1.12
You should proceed to save your Excel Workbook before your work is lost. Remember to save your
file with the extension xlsm, which means Excel Macro Enabled Workbook, otherwise your VBA will
not run when you open it the next time.
Figure 1.13 Saving File with Extension xlsm
In addition, Visual Basic Editor also allow you to insert modules and UserForms to build more
advance VBA. Usually the module allows you to develop customized functions whereas the
UserForm allows you to build more powerful applications. We will discuss module and UserForm in a
later chapter.
You can also learn Excel VBA 365 programming by creating and editing macros. Macro is a record
and playback tool that records and plays back Excel worksheet activities performed by the
user. Macros save time as they automate repetitive tasks. It is a programming code that runs in
an Excel VBA environment. You can edit a macro as well as creating new macros using Visual Basic
syntaxes.
To record a macro, click on the Record Macro button in the Developer environment, as shown in
Figure 1.14
Figure 1.14
Upon clicking the Record Macro button, a dialog box will appear and prompts you to enter the macro
name. The macro name cannot have space between characters, underscore is allowed. Following
are a few rules in naming a macro:
If you did not follow the rules, the dialog as shown in Figure 1.16 will appear.
Figure 1.16
Let us create a macro named Test_Macro. Next, click OK to start recoding the macro. Perform some
activities on the worksheet like entering some numbers and add those numbers, then stop the macro
recording.
To view the macro you have just created, click the Macros button and you can see the newly created
macro as shown in Figure 1.17. You can run, edit or delete the macro.
Figure 1.17
Let us edit the macro. When you click on the Edit button, you will be able to see the macro code in
the VBE, as shown in Figure 1.18. The code is the same as the code in a VB sub procedure which
starts with a Sub keyword and an End Sub keyword.
Figure 1.18
Let us create a macro from scratch instead of recoding a macro. To create a macro, click on Macros
button and type in a name, as shown in Figure 1.19.
Figure 1.19
Click create to enter the VBE, and type come codes as shown in Figure 1.20.
Figure 1.20
The macro code is using the VB syntaxes. In the macro, we declared a variable rng to store the
range value. By using the keyword With and the Range method, the macro formats the targeted
range of cells using the font properties, the interior object and the color property. The macro will also
populate the cells with a value of 100. We shall learn more about object and properties in later
lessons. Save the macro and then click the run (a little green triangle on the tool bar) button or press
F5 to run the macro. A dialog will appear prompting you to run, edit or delete the macro as shown in
Figure 1.21.
Figure 1.21
Choose Run to execute the macro and you go back to the worksheet to see the results, as shown in
Figure 1.22
Figure 1.22
This is a macro that calculates the salary based on the wage and hours worked.
When you run the macro, it will call the sub procedure with two arguments, i.e. wage and hours. The
values specified by the macro will be passed to the sub procedure to compute the salary. The output
is as shown in Figure 1.23
Figure 1.23
This macro adds two numbers input by the user via input boxes and present the sum in a message
dialog.
Sub Cal_Sum()
Dim x As Single, y As Single
x = InputBox("Enter first number")
y = InputBox("Enter second number")
sum x, y
End Sub
Sub sum(a As Single, b As Single)
MsgBox ("sum=" & a + b)
End Sub
The outputs are shown in Figure 1.24, Figure 1.25 and Figure 1.26
Figure 1.24
Figure 1.25
Figure 1.26
Example 1.6 A Macro that Populates Cells using the For…Next Loop
This macro employs a For…Next loop to populate a range of cells on the worksheet. (you will learn
more about For…Next loop in a later chapter.)
Sub Loop_macro()
Dim i, j As Integer
For i = 1 To 10
For j = 1 To 5
Cells(i, j).Value = i + j
Next
Next
End Sub
When you run the program, the cells in the range A1:E10 will be populated, as shown in Figure 1.27
Figure 1.27
Example 1.7 A Macro that Populates the Cells with Characters using the Chr() Function.
This macro generates random characters based on the Chr() function and the ASCII codes.
Sub Random_Chr()
Dim m As Integer
For i = 2 To 6
For j = 2 To 6
m = Int(26 * Rnd) + 65
Sheet1.Cells(i, j) = Chr(m)
Next
Next
End Sub
Range("cell Name").Value=K
or
Range("Range of Cells").Value=K
Value is the property of the Range object and k is a numeric value or a string.
In this example, clicking the command button will fill cell A1 to C6 with the value of 100, change its
background color to blue and its font color to yellow.
Figure 1.14
This example apply the Do Loop to populate cells(1,1) to cells(6,3) with numbers that
follow the formula specified in the code. For example, when i=2, the value of cells(2,2) is
2+2=4. On top of that, it also set the background for the specified range to yellow and the font
color to red.
Private Sub CommandButton1_Click()
i = 1
Do
Cells(i, 1) = i
Cells(i, 2) = i + 1
Cells(i, 3) = i + 2
i = i + 1
Loop Until i > 6
Range("A1:C6").Interior.Color = vbYellow
Range(Cells(1, 1), Cells(6, 3)).Font.Color = vbRed
End Sub
This is a macro that accepts inputs from the user and calculate the sum. When you run the macro,
the user will be prompted to enter two numbers via two input boxes, then sum them up.
Sub Cal_Sum()
Dim x As Single, y As Single
x = InputBox("Enter first number")
y = InputBox("Enter second number")
sum x, y
End Sub
When you run the macro, two input boxes will appear to alert the user to enter two numbers, then
present the answer via a dialog message, as shown in Figure 1.16, Figure 1.17 and Figure 1.18.
where program_label is the section of code that is designed by the programmer to handle the
error committed by the user. Once an error is detected, the program will jump to the
program_label section for error handling. You also need to add the statement Exit Sub to prevent
the program from jumping to error handling section even though the inputs were correct.
err_handler:
MsgBox "Invalid division, please try again"
End Sub
The program will display the error message “Invalid division, please try again” if the user enters
letters instead of numbers or enter the second number as zero, as shown in Figure 1.16
Figure 1.16
Example 1.13 Nested Errors Handling
By referring to Example 1.6, it is better to alert the user the types of error he or she has committed,
such as entering non-numeric data like letters or enter zero as denominator. It should be placed in
the first place as soon as the user input something in the input box. And the error handler label
rror_handler2 label. This means the second
error_handler1 for this error should be placed after the e
error handling procedure is nested within the first error handling procedure. Notice that you must put
an Exit Sub for the second error handling procedure to prevent to execute the first error handling
procedure again. The code is as follow:
error_handler2:
Figure 1.17
Figure 1.18
Additionally, you can use the keyword Resume Next to prevent error message from appearing and
branch back to the section of the program where error occurred.
"
Like the mailboxes, each variable must be given a name. To name a variable in Excel VBA 365, you
must follow the following set of rules:
Examples of valid and invalid variable names are displayed in Table 2.1
My_Car My.Car
ThisYear 1NewBoy
Long_Name_Can_beUSE He&HisFather *& is not acceptable
In Excel VBA 365, we must declare the variables before using them. We declare a variable by
assigning a name and a data type. Excel VBA 365 data types can be divided into two types, the
numeric data types and the non-numeric data types.
Numeric data types are types of data that consist of numbers. In Excel VBA 365, the numeric data
are divided into 7 types as summarized in Table 2.2.
Non-numeric data types are data that cannot be manipulated using arithmetic operators. They
comprise string, date, Boolean and more, as summarized in Table 2.3
You may declare the variables implicitly or explicitly. For example, sum=text1.text means that the
variable sum is declared implicitly and ready to receive the input in Textbox1. For explicit
declaration, variables are declared in the general section of the code window using the Dim
statement. The syntax is as follows:
You may also combine the variables into one line, separating each variable with a comma.
If the data type is not specified, Excel VBA 365 will automatically declare the variable as a Variant.
For string declaration, there are two possible formats, one for the variable-length string and another
for the fixed-length string. For the variable-length string, just use the same syntax as Example 2.1
above. However, for the fixed-length string, you must use the syntax as shown below:
This is a payroll app that calculate the salary based on wage per hour and hours worked. In this
example, we declared four types of variables, namely the string, date, currency and Boolean. The
declaration Dim college As String * 10 implies that the variable college can only holds 10
characters. In addition, we use the If…Then…Else statement to determine whether the employee
entitle a promotion.
The code
End Sub
The output is as seen in Figure 2.1
Figure 2.1
You can notice that the College name has been truncated to just 10 characters (including spacing).
When Option Explicit is included in the program code, every variable must be declared using
the Dim keyword. Any variable that is not declared or wrongly typed will produce the “Variable not
defined” error. The error must be corrected before the program can continue to run.
Example 2.3 Using Option Explicit to Catch Typo Errors
This example uses the Option Explicit keyword and it demonstrates how a typo is being tracked.
Option Explicit
Private Sub CommandButton1_Click()
Dim YourName As String
Dim password As String
YourName = "John"
password = 12345
Cells(1, 2) = YourNam
Cells(1, 3) = password
End Sub
The typo is YourNam and so the error message ‘variable not defined” will be displayed and the
program is suspended, as shown in Figure 2.2. The error Yournam will also be highlighted as shown
in Figure 2.3.
Figure 2.2
Figure 2.3 Error message due to typo error
After declaring several variables with the Dim statements, we can assign values to them. The syntax
of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The expression can be a
mathematical expression, a number, a string, a Boolean value (true or false) and more. Here are
some examples:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = False
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
2.4 Performing Arithmetic Operations
To compute numeric values, we shall use arithmetic operators. In Excel VBA 365, the symbols for
arithmetic operators are different from normal mathematical operators except for + and -. For
example, multiplication is * and division is /. Besides. we must differentiate between / and \, where /
is a normal division whilst \ is an integer division. Integer division \ discards the decimals. For
example, 27\5 is 5. The Excel VBA 365 arithmetic operators as shown in Table 2.3.
^ Exponential 2^4=16
* Multiplication 4*3=12
/ Division 12/4=3
This example calculates the total mark and the average mark of an examination result. We declared
four variables as Single and another two variables as Double. In the code, we use
Worksheetfunction.sum to add the marks and Worksheetfunction.count to count the number
of subjects.
The Code
Option Explicit
Private Sub Cmd_Calculate_Click()
Dim mark1, mark2, mark3, mark4 As Single
Dim total, average As Double
mark1 = 60
mark2 = 75
mark3 = 85
mark4 = 54
Cells(2, 2) = mark1
Cells(3, 2) = mark2
Cells(4, 2) = mark3
Cells(5, 2) = mark4
total = WorksheetFunction.Sum(Range(Cells(2, 2), Cells(5, 2)))
average = total / WorksheetFunction.Count(Range(Cells(2, 2), Cells(5, 2)))
Cells(6, 2) = total
Cells(7, 2) = average
End Sub
The output is shown in Figure 2.4
Figure 2.4
Example 2.5 Concatenation of Strings
In this example, three variables are declared as string. The variable firstName and the variable
secondName will receive their data entered by the user into Cells(1,1) and cells(2,1) respectively.
You will notice that performing arithmetic operation on strings will result in the concatenation of the
strings, as shown in Figure 2.5.
Option Explicit
Private Sub CommandButton1_Click()
Dim secondName As String
Dim yourName As String
firstName = Cells(1,1)
secondName = Cells(2,1)
yourName = firstName + " " + secondName
Cells(3,1) = yourName
End Sub
When we work with a single item in Excel VBA 365, we only need to declare one variable. However,
if we need to deal with a list of items, we need to declare an array of variables instead of using a
variable for each item. For example, if we need to enter 100 names, instead of declaring 100
different variables, we need to declare only one array.
An array is a group of variables with the same data type and name. We differentiate each item in the
array by using subscript, the index value of each item. For example, Studentname (1), Studentname
(2), Studentname (3) …Studentname(n)
We use the Dim statement to declare an array just as the way we declare a single variable. In Excel
VBA 365 we can have a one-dimensional array, two-dimensional array or even a multidimensional
array (up to 60)
In this example, we define an array StudentName comprising five names using the Dim keyword.
We include an InputBox to accept input from the user. We also use the For…Next loop to accept the
input five times and display the five names from cell A1 to cell E1. The code is as follows:
Private Sub CommandButton1_Click( )
Dim StudentName(1 to 5) As String
For i = 1 To 5
StudentName(i) = InputBox(“Enter student Name”)
Cells(i, 1) = StudentName(i)
Next
End Sub
* You can also declare the array using Dim StudentName(5) As String When we run the
program, an input box will appear, as shown below. This input box will repeat five times and let the
user enter five names, as shown in Figure 2.6.
Figure 2.6
Figure 2.7
You can also declare more than one array on a single line. In Example 2.7, we declare three arrays
in a single line, separated by commas.
When we run the program, three input boxes will appear consecutively to let the user enter the
student name, the student ID and then the student mark. The process will repeat three times until
the particulars of all three students have been entered. The three input boxes and the output images
are shown below:
Figure 2.8
Figure 2.9
Figure 2.10
Figure 2.11
Multidimensional arrays are often needed when we are dealing with a more complex database,
especially those that handle a large amount of data. Data are usually organized and arranged in
table form; this is where the multidimensional arrays come into play. However, in this tutorial, we are
dealing only with the two-dimensional array. A two-dimensional array can be represented by a table
that contains rows and columns, where one index represents the rows and the other index represent
the columns.The statement to declare a two-dimensional array is
Where num1 is the suffix of the first dimension of the last element and num2 is the suffix of the
second dimension of the last element in the array. The suffixes of the element in the array will start
with (0, 0) unless you set the Option Base to 1. In the case when the Option Base is set to 1, then
the suffixes of the element in the array will start with (1, 1). For example,
Table 2.1
If you set the option base to 1, then there will be only 9 elements, i.e from Score(1,1) to Score(3,3).
However, if you want the first element to start with suffixes (1,1) you can also use the following
format of declaration:
If a company wants to track the performance of 5 salespersons over a period of 2 days, you can
create a 5×2 array in Excel VBA 365, denoted by a 5X 2 table in a worksheet. Therefore, you can
write the following VBA code using a nested For loop.
When the user runs the program, the input box that will prompt the user to enter salesperson's
name, as shown in the Figure 2.12
Figure 2.12
Next, you will be asked to enter the sales volume for day 1 and day 2, as shown in Figure 2.13 and
Figure 2.14.
Figure 2.13
Figure 2.14
After entered data for five salespersons, you will obtain a table as shown in Figure 2.15
Figure 2.15