Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Table of Contents
Table of Contents
Introduction
A supplementary Excel file to share
Chapter 1: Knowing your tools
Developer tab
Visual Basic Editor
Customizing VBE
Immediate window
Exercise 1-1: Executing a comparison statement in the Immediate window
Exercise 1-2: Entering a value into a cell from the Immediate window
Object Browser
Exercise 1-3: Exploring the properties of an object
Exercise 1-4: Exploring the properties and methods of an object
Macro recorder
Exercise 1-5: Recording a macro
VBA Help system
Exercise 1-6: Checking the syntax for a structure
Exercise 1-7: Exploring the VBA Help system in Excel 2007 and 2010
Chapter 2: Knowing the places to store your VBA code
Types of VBA modules
Sample procedures in a standard VBA module
A simple Sub procedure: Color banding
Exercise 2-1: Executing a Sub procedure by using the Macro dialog box
Exercise 2-2: Executing a Sub procedure by using a shortcut key combination
Exercise 2-3: Making a Sub procedure available to all opened workbooks
A simple Sub procedure: Hiding the cells contents
Exercise 2-4: Executing a Sub procedure by using the Macro dialog box
A simple Function procedure: A power-of-three function
Exercise 2-5: Using a custom function in a worksheet formula
Exercise 2-6: Calling a custom function from the Immediate window
Introduction
Visual Basic for Applications (VBA) is the programming language built into Microsoft
Office applications (such as Microsoft Excel, Microsoft Word, Microsoft Access, and
Microsoft Outlook) to automate various tasks in their own environment and to work with
other applications.
This book focuses on VBA in Microsoft Excel for Windows. The discussions in the book
are applicable to Excel 2007, Excel 2010, Excel 2013, and Excel 2016, unless otherwise
stated. It starts with Chapter 1, which is to get you familiarize with some essential tools
that help you to write your VBA programs. Chapter 2 covers the places where you should
store your VBA code. Chapter 3 is the fundamentals of programming in VBA. It provides
you a quick reference in writing syntax error-free VBA code, in debugging, and in
handling errors. Chapter 4 offers some other tips on VBA programming.
This book is for readers that are totally new to Excel VBA, but should have a basic
understanding of programming language, such as C or Python. The reader should be an
average Excel user who knows, for example, what an array formula is. If you are new to
Excel, please teach yourself Excel before exploring the chapters. You may refer to another
book written by me entitled Learn Microsoft Excel 2010-2016 for Windows in 24
Hours - A jumpstart to be an intermediate user, which was written for those who are new
to Excel.
This book does not serve as a comprehensive reference for intermediate users.
Nevertheless, it is a jumpstart for beginners to learn Excel VBA. It is also served as a
foundation for my future books and other references that are beyond the reach of
beginners.
I hope this book will shorten your time to teach yourself Excel VBA and serve as a quick
reference in writing error-free and working VBA programs in realizing your goal. Let
Excel VBA work for you.
Developer tab
By default, the Developer tab in the Excel Ribbon is hidden. Most often when writing
programs, you need to access some of the commands on this tab. Hence, it is essential to
turn it on by executing the steps in the following table:
Version
Steps
1. Click the File tab and choose Options to display the Excel Options
dialog box.
Excel 2010,
Excel 2013, or
Excel 2016
Excel 2007
Note: Later in the book, when accessing a command on the Ribbon or on a menu bar, I
will just state choose File | Options, for example.
Customizing VBE
In VBE, choose Tools | Options from the menu bar to display the Options dialog box. In
the Editor tab, make sure all check boxes are ticked. After sometimes writing VBA code
and knowing the programming syntax, you may want to unselect the Auto Syntax Check
option.
The Auto List Members and Auto Quick Info options are particular useful. While you type
the name of an object followed by a dot (also known as a period) in the code window and
in the Immediate window, Auto List Members allows a list of members for that object to
be displayed automatically. You can then use the up- and down-arrow keys and the Tab
key to select an item from the list.
If you type the name of a function, property, or method followed by an opening
parenthesis, Auto Quick Info allows the information about the arguments available for the
function, property, or method to be displayed automatically.
In the Editor Format tab, you can see the default colors for text in the code window. The
table below shows some of them.
Text in
window
the
code
Default color
Normal code
Black
Keywords
Blue
Comments
Green
Syntax errors
Red
Immediate window
The Immediate window is most useful to execute a single code statement and get the result
immediately, without having to create a procedure. I discuss procedures later in Chapter 3.
Exercise 1-1: Executing a comparison statement in the Immediate window
Type the following statement, for example, in the Immediate window and press enter to
get the immediate result for a logical comparison:
? 2>3
It returns False.
Exercise 1-2: Entering a value into a cell from the Immediate window
Type the following statement, for example, in the Immediate window and press enter:
ActiveCell = Hello
The statement above enters the word Hello into an active cell in a worksheet of a
workbook. At any particular time, only one workbook, one worksheet of the workbook,
and one cell in the worksheet can be active. Press Alt-F11 to switch to Excel and see the
result in the worksheet.
Object Browser
The Object Browser window allows you to browse a complete list of classes, the
properties, methods, and events in the classes, and VBA built-in constants in any object
libraries. When you are working with other applications (such as Microsoft Word and
Internet Explorer), the libraries associated with those applications need to be included in
your VBA project by setting references. I discuss events and the way of setting references
later in Exercise 3-2 of Chapter 3. Working with other applications is only discussed in my
future book for intermediate users. In addition, Object Browser also shows the procedures
written by you.
Exercise 1-3: Exploring the properties of an object
To browse the properties of an object, for example the Font object, execute the following
steps:
1. In VBE, choose View | Object Browser from the menu bar or press F2 to display
Object Browser.
2. In the Search box of Object Browser, type Font and press Enter. See Figure 1-1.
The Search Results window displays any items that match the search text, in this
case, Font.
3. In the list box of the Search Results window, you can see that Font is a class under
the Class header, and Font is also a member of other classes under the Member
header. If you select any Font under the Member header, its class is then displayed
in the Classes window. Select the Font class in the Search Results window.
4. In the Classes window, Font is selected. Under the Members of Font header, the
members of the Font class are displayed. In the case of the Font class, all members
are properties. For other class, such as the Worksheet class, it can have properties,
methods, and events as its members. Select Underline.
In the bottom pane, it shows more information about the selected item, in this case,
Underline.
5. Press F1 to access a help page about this member.
If to access a help page about the class itself, press F1 when the class is selected
either in the Classes window or in the Search Results window. Help pages are in the
VBA Help system, which will be discussed later in this chapter.
Exercise 1-4: Exploring the properties and methods of an object
To browse the properties and methods of an object, for example the Range object, execute
the following steps:
1. In VBE, choose View | Object Browser from the menu bar or press F2 to display
Object Browser.
2. In the Search box of Object Browser, type Range and press Enter.
The Search Results window displays any items that match the search text, in this
case, Range.
3. In the Classes window, the classes are arranged alphabetically. Look for the Range
class and click on it.
4. Under the Members of Range header, you can see the Font property is one of its
members. There are many other properties and methods. Clear is one of the
methods.
5. Press Alt+F11 to activate Excel.
6. Enter some text into cell B5 and do some formatting to the cell.
7. Press Alt+F11 to activate VBE.
8. In the Immediate window, type the following statement and press Enter to see how
the Clear method clears everything in cell B5.
Range(B5).Clear
The statement above shows a typical way of referencing a member of an object by
using a dot (also known as a period).
Macro recorder
The macro recorder converts your Excel actions into VBA code. Although it does not
always generate the most efficient code, but it is an extremely useful tool that provides
you clues on how to proceed your coding and it allows you to discover the VBA built-in
constants, the properties and methods of objects that you are not familiar with.
Macro1 Macro
Range(B5).Select
Selection.Font.Bold = True
Selection.Font.Underline = xlUnderlineStyleSingle
With Selection.Font
.Color = -16776961
.TintAndShade = 0
End With
ActiveCell.FormulaR1C1 = Hello
Range(B6).Select
End Sub
The generated lines of code are known as a macro, which is a Sub procedure. Even though
it is not the most efficient code, but it does provide clues on how a program in changing
the font of a cell can possibly be written and allows you to know the Range and Font
objects, the Selection, Font, Bold, Underline, Color, TintAndShade, ActiveCell, and
FormulaR1C1 properties, the Select method, and the xlUnderlineStyleSingle built-in
constant.
The macro can be improved by removing the unnecessary actions of selecting cells and
the default value of the TintAndShade property:
Range(B5).Font.Bold = True
Range(B5).Font.Underline = xlUnderlineStyleSingle
Range(B5).Font.Color = -16776961
Range(B5).FormulaR1C1 = Hello
Its efficiency can be further improved by using the With-End With construct. The
construct reduces the number of dot references that VBA needs to process.
With Range(B5).Font
.Bold = True
.Underline = xlUnderlineStyleSingle
.Color = -16776961
End With
Range(B5).FormulaR1C1 = Hello
be created in those modules. Nevertheless, the samples do provide you ideas to place your
VBA code in the right modules, and provide you the reasons why the code listings in this
book are stored in certain modules. If you study some sample code listings from other
references, such as books and the Internet, you should find no exception in where VBA
code should be stored.
Selection.NumberFormat = ;;;
End Sub
Exercise 2-4: Executing a Sub procedure by using the Macro dialog box
After storing the HideCellContent procedure in a standard VBA module, execute the
following steps to run the sample procedure:
1. In a worksheet, enter something (text, numbers, or formulas) into a few cells.
2. Select the cells with something entered in Step 1.
3. Press Alt+F8 to display the Macro dialog box.
4. Select the macro named HideCellContent, and click Run to hide the contents.
The contents of the selected cells are not actually totally hidden. By selecting one of
the cells, you can still view its contents in the formula bar.
Power3 = 3 ^ x
End Function
Exercise 2-5: Using a custom function in a worksheet formula
To use the preceding sample custom function in a worksheet formula, execute the
following steps:
1. Press Alt+F11 to activate Excel.
2. Select any cell in a worksheet and enter the following formula, for example:
=Power3(4)
It returns 81, which is 3 to the power of 4.
Exercise 2-6: Calling a custom function from the Immediate window
To call the function from the Immediate window, enter the following statement, for
example:
? Power3(2)
It returns 9, which is 3 to the power of 2.
Exercise 2-7: Calling a custom function by a procedure in other module
A custom function (or a procedure, in general) stored in a standard VBA module can be
called not only by procedures in its own module, but also by procedures in other modules
if it is declared as a public function (or public procedure, in general). These other modules
can be other standard VBA modules, workbook modules, sheet modules, UserForm
modules, and class modules.
To call the custom function Power3 (which is stored in a standard VBA module) from
other module, execute the following steps:
1. Add a standard VBA module to the project of the workbook that stores the custom
function.
Note: Calling a custom function by procedures in other workbooks will be discussed
in Exercise 3-2.
2. In the code window of the newly added module (or in the code window of the
workbook module or a sheet module), enter the following Sub procedure:
Sub TestPower3()
Debug.Print Power3(4)
End Sub
The Debug.Print method executes the expression Power3(4) and sends the output of
the execution to the Immediate window.
If to call the custom function from the workbook module and a sheet module, copy
and paste the TestPower3 procedure into those modules.
3. Press F5 or click the triangle icon on the Standard toolbar to execute the
TestPower3 procedure.
In this case, it returns 81 in the Immediate window.
VBA code is by changing the ScrollArea property in the Properties window of the
worksheet. In VBE, press F4 (or in Excel, choose Developer | Controls | Properties) to
display the Properties window.
Figure 2-1: A Userform to collect information from a user.
To create the UserForm, execute the following steps:
1. Start a blank workbook, or open an existing workbook.
2. Press Alt+F11 to activate VBE.
3. Add a UserForm module to the project of the workbook by executing the following
steps:
a. In the Project Explorer window, right-click the projects name of the
workbook.
b. Choose Insert | UserForm from the shortcut menu.
By default, it is named UserForm1. You can change its name in the Properties
window. If the Properties window is not visible, press F4.
A blank UserForm is then created with a floating Toolbox window. If the Toolbox
window is not visible, choose View | Toolbox from the menu bar.
4. In the Properties window of the UserForm,
a. Change the Caption property to Create Multiplication Table.
b. Change the Name property to MTableUF.
If the Properties window is not visible, press F4.
5. Add a frame, three option buttons, and a command button to the UserForm by
choosing the controls from Toolbox and drawing the controls on the UserForm. See
Figure 2-1.
You may use the buttons on the UserForm toolbar to align and distribute the
controls. If the toolbar is not visible, choose View | Toolbars | UserForm from the
menu bar.
6. Set the following properties of the controls, as listed in the table below:
Control/Property Name
Caption Accelerator
Frame
Frame1
Select a
number
NA
Option button 1
Option3
Option button 2
Option4
Option button 3
Option5
Command button
CreateButton Create
UserForm.
2. Enter the following code for the event handler and Sub procedure in the code
window:
Private Sub CreateButton_Click()
Dim n As Long
If Me.Option3 Then n = 3
If Me.Option4 Then n = 4
If Me.Option5 Then n = 5
Call CreateMTable(n)
Unload Me
End Sub
Note: Me refers to the UserForm object.
Private Sub CreateMTable(n As Long)
To create a multiplication table of n
on an active worksheet
Dim i As Long
With ActiveSheet
For i = 1 To 12
.Cells(i, 1) = _
i & x & n & = & i * n
Next i
.Columns(A:A).AutoFit
End With
End Sub
To create a command button on a worksheet and an event handler for an event of clicking
the command button, execute the following steps:
1. Press Alt+F11 to activate Excel, and select a worksheet.
2. Choose Developer | Controls | Insert and select Command Button (ActiveX
Control).
3. Draw the button on the worksheet.
4. Double-click the command button to activate the code window of the sheet
module.
By default, the Click event is selected from the Procedure drop-down list, which is
located on the top-right corner of the code window.
5. Enter the following event handler into the code window:
Private Sub CommandButton1_Click()
MTableUF.Show
End Sub
6. Press Alt+F11 to activate Excel and choose Developer | Controls | Design Mode to
exit design mode.
Or in VBE, choose Run | Exit Design Mode from the menu bar.
7. Click the command button on the worksheet to show the UserForm.
8. Select an option and click the Create button on the UserForm to generate a
multiplication table.
As mentioned in Introduction, this book assumes that you should have a basics
understanding of programming language, such as C or Python. This chapter recaps the
fundamentals of programming in the environment of Excel VBA.
Data types
A data type, such Integer or Boolean, is a classification of data. It determines the space the
data occupies in memory, the values the data can store, and the operations can be done on
the data. The following table lists the supported data types in Excel VBA with their
storage sizes and value ranges.
Data
type
Storage
size
Range of values
Byte
1 byte
0 to 255
Boolean
2 bytes
True or False
Integer
2 bytes
-32,768 to 32,767
Long
4 bytes
-2,147,483,648 to 2,147,483,647
4 bytes
8 bytes
-1.79769313486231E308 to
-4.94065645841247E-324 for negative values;
4.94065645841247E-324 to 1.79769313486232E308
for positive values
Currency
8 bytes
-922,337,203,685,477.5808 to
922,337,203,685,477.5807
Decimal
14 bytes
+/-79,228,162,514,264,337,593,543,950,335 with no
decimal point;
+/-7.9228162514264337593543950335 with 28 places
to the right of the decimal
Date
8 bytes
Object
4 bytes
String
(variablelength)
10 bytes +
string length
String
(fixed-length)
Length of
string
Variant
(with
numbers)
16 bytes
Variant
(with
characters)
22 bytes +
string length
User-defined
(using Type)
Bytes
required by
elements
Single
Double
A Variant is a special data type. If a variable is declared without explicitly stating its data
type, it is then, by default, of data type Variant. A variant variable can hold any kind of
data, including special values such as Empty, Error, Nothing, and Null.
The data type of a variant variable changes when needed, depending on what manipulation
is done on the variable. The following listing illustrates the point by checking the data
type of a variant variable.
Sub CheckVariantDataType()
StaffName As String * 30
Addr(1 To 2) As String
Age As Byte
End Type
The definition of a custom data type must be placed at the top of a VBA module before
any procedures.
Examples of declaring variables
To declare a variable of data type Boolean:
Dim FileOpened As Boolean
To declare an integer variable:
Dim Counter As Integer
To declare a variable of data type Long:
Dim NextRow As Long
To declare a variable of data type Date:
Dim Timer1 As Date
To declare a variable of data type String:
Dim FileName As String
To declare a string variable with a specified number of
characters:
Dim FileName As String * 20
To declare a variable of data type Object:
Dim objElements As Object
To declare a variable without explicitly stating a data
type:
Dim Temp
The variable is then, by default, of data type Variant.
To declare multiple variables on a single line:
Dim i As Long, j As Long
The variables i and j are of data type Long.
To declare multiple variables on a single line:
Dim i, j As Long
Only j is of data type Long. Since i is in fact declared
without explicitly stating a data type, it is of data type
Variant, by default.
To declare an object variable that can, but not yet,
contain a reference to a worksheet object:
Dim ws As Worksheet
The variable ws holds the special value Nothing until it
is assigned an object reference using the Set statement,
for example:
Set ws = ActiveSheet
To declare an object variable:
Dim coln As Collection
To create an object (using the New keyword) and assign
its reference to an object variable:
Set coln = New Collection
The object reference (to the newly created Collection
object) is assigned to the variable coln using the Set
statement.
A shortcut to declare an object variable, to create an
object, and to assign the reference of the object to the
object variable:
Dim coln As New Collection
To declare a two-dimensional array of integers:
Dim iMatrix(1 To 3, 1 To 4) As Integer
To declare a dynamic array of custom data types:
Dim uCACommittee() As uStaffInfo
To declare a dynamic array of variants:
Dim vMyArray()
I discuss arrays later in this chapter.
Example of how a
constant is declared
Scope of
visibility
All modules
Private Const Dept As
String = DXC
All
procedures
Const Dept As String = in that
module
DXC
Within a
procedure (after
the Sub or
Function
statement)
Location where
a variable is
declared
Example of how a
variable is declared
Scope of
visibility
All modules
Private myStr As
String
Dim myStr As String
Within a
procedure (after
the Sub or
All
procedures
in that
module
Only in that
procedure
Function
statement)
The Public and Private keywords can only be used before the first procedure in a module.
All public constants and variables declared in a VBA module with the Public keyword can
be used in all modules. If they are declared in a non-standard VBA module (such as a
sheet or workbook module), to use them from other modules you need to precede their
names with the module name. For example, a public variable named myStr declared in a
worksheet module named Sheet1 can be accessed with the following expression:
Sheet1.myStr
A module-level constant, a constant that is declared in a module before the first procedure,
without using the Private keyword is private to the module by default. A module-level
variable either declared with the Private or Dim keyword is private to the module.
All variables and constants declared within a procedure can only be accessed within the
procedure. A procedure-level variable declared with the Static keyword (the keyword that
can only be used within a procedure to declare variables) retains its value between
procedure calls.
Exercise 3-1: Testing a static variable
To understand more about a static variable, execute the following steps:
1. Enter the following Function procedure into the code window of either a new or an
existing standard VBA module:
Function Counter() As Long
To return the number of times it is called
The variable x preserves its value
between calls
Static x As Long
x = x + 1
Counter = x
End Function
2. Enter the following Sub procedure either into the code window of the module
where the Counter function is stored in or into the code window of other module:
Sub TestCounter()
Dim i As Long
For i = 1 To 4
Debug.Print Counter()
Next i
End Sub
3. Choose Run | Run Sub/UserForm or press F5 to execute the Sub procedure.
Observe the values displayed in the Immediate window. The static variable x (in the
Counter function) retains its value.
4. In the Immediate window, enter the following statement to call the function
another time:
? Counter()
It returns 5. That is, the fifth time the function is called.
5. Press Alt+F11 to activate Excel, and enter the following formula into any cell:
=Counter()
It returns 6. That is, the sixth time the function is called.
If-Then structure
The following are two variations of an If-Then structure followed by one or two simple
examples for each variation.
Syntax for an If-Then structure
If condition Then statement(s)
Example 1
If A > 3 Then Cnt = Cnt + 1
Example 2
If A > 3 Then Cnt = Cnt + 1 : Sum = Sum + A
Note: A colon is to place two statements on a single line.
Syntax for an If-Then structure
If condition Then
[statement(s)]
End If
Note: A pair of square brackets indicates an optional part of
the structure.
Example
If A > 3 Then
Cnt = Cnt + 1
Sum = Sum + A
End If
If-Then-Else structure
Cnt = Cnt + 1
Else
B = B + 1
End if
Syntax for an If-Then-Else structure
If condition1 Then
[statement(s)]
ElseIf condition2 Then
[statement(s)]
Else
[statement(s)]
End If
Example
If Score >= 8 Then
MsgBox A
ElseIf Score > 3 And Score < 8 Then
MsgBox B
Else
MsgBox C
End If
Alternatively, the preceding structure that uses ElseIf can be replaced with the following
structure, which is more intuitive and easier to understand.
Syntax for an If-Then-Else structure
If condition1 Then
[statement(s)]
Else
If condition2 Then
[statement(s)]
Else
[statement(s)]
End If
End If
Example
If Score >= 8 Then
MsgBox A
Else
Case Is >= 8
MsgBox A
Case 4 To 7
MsgBox B
Case Else
MsgBox C
End Select
Example 2
Select Case Round(Rate, 2)
For-Next loop
A For-Next loop executes a group of statements for a specified number of times.
Syntax for a For-Next loop
For counter = start To end [Step step]
[statement(s)]
[Exit For]
[statement(s)]
Next [counter]
Example 1
Dim i As Long
For i = 2 To 10 Step 2
Debug.Print i, returns 2 4 6 8 10
Next
Example 2
Dim i as Long
For i = 9 To 1 Step -2
Debug.Print i, returns 9 7 5 3 1
Next i
The optional Exit For statement in a For-Next loop is often used after evaluating of some
condition, for example in an If-Then structure, and control is then transferred to the
statement immediately after the For-Next loop.
A For Each-Next loop executes a group of statements for each element in a collection.
Syntax for a For Each-Next loop
For Each element In group
[statement(s)]
[Exit For]
[statement(s)]
Next [element]
Example
Dim ws As Worksheet
For Each ws In Worksheets
Debug.Print ws.Name
Next
Do loop
A Do loop is either a Do-While loop or a Do-Until loop. Unlike For-Next and For EachNext loops that execute for a specified number of times, a Do loop executes as long as the
While condition in the loop is True or the Until condition in the loop becomes True.
Syntax for a Do-While loop
Do [While condition]
[statement(s)]
[Exit Do]
[statement(s)]
Loop
Example
Dim i As Long: i = 2
Do While i <= 10
Debug.Print i, returns 2 4 6 8 10
i = i + 2
Loop
Debug.Print i, returns 2 4 6 8 10
i = i + 2
Loop
If to execute at least once the statements inside a Do loop, simply move the While or Until
condition of the Do loop and place it right after the Loop keyword, as shown below.
Syntax for a Do-While loop that executes at least once
Do
[statement(s)]
[Exit Do]
[statement(s)]
Loop [While condition]
Example
Dim i As Long: i = 99
Do
Debug.Print i, returns 99
i = i + 2
Loop While i <= 10
Syntax for a Do-Until loop that executes at least once
Do
[statement(s)]
[Exit Do]
[statement(s)]
Loop [Until condition]
Example
Dim i As Long: i = 99
Do
Debug.Print i, returns 99
i = i + 2
Loop Until i > 10
The optional Exit Do statement in a Do loop is often used after evaluating of some
condition, for example in an If-Then structure, and control is then transferred to the
statement immediately after the Do loop.
Comparing strings
There are three ways to compare a pair of strings: comparison operators (<, <=, >, >=, =,
and <>), the Like operator, and the StrComp function.
The Option Compare statement appeared at the top of a VBA module before any
procedures specifies the string comparison method (Binary for case-sensitive
comparisons, Text for case-insensitive comparisons, or Database only be used within
Microsoft Access) in the module. If a module does not have the Option Compare
statement, the default comparison method is Binary.
Comparison operators
Type the following statements into the Immediate window and press Enter after each.
? Amy < Ann returns True
? Amy <= Ann returns True
? Amy = Ann returns False
? Amy > Ann returns False
? Amy >= Ann returns False
? Amy <> Ann returns True
[CharacterList]
[!CharacterList]
Example statement using the
Like operator
MyStr is six-characters
long, starts with an
alphanumeric character
and ends with a digit.
The StrComp function
The syntax for the StrComp function is as below:
StrComp(string1, string2[, compare])
Similar to comparison operators, the StrComp function performs a character-by-character
comparison between two strings. The third argument in the function provides an option to
ignore the Option Compare statement in a module. The return values of the StrComp
function are as shown in the following table.
Condition
Return value
-1
string1 = string2
Null
InStrRev
Right
Mid
LTrim,
RTrim
Trim
UCase
StrConv
Space
String
Note: The Replace function has six arguments
and other functionalities. For example, if to
replace only the first occurrence of a specified
substring in a string, set the fifth argument to 1,
as shown in an example below:
Replace(a12012b, 12, B, , 1)returns
aB012b.
CStr(expression)
Convert an expression to a string.
CStr
Format
Join
Filter
Join(Filter(Split(This is an example),a),|)
returns
an|example.
The Filter function in the example above
returns an array of two elements: an and
example, in which both have the character
a.
Returning a character
Chr(charcode)
A character associated with a character code.
Chr
Chr(65) returns A.
Note: To return a character code associated
with a character, use Asc(). For example:
Asc(A) returns 65.
intScales(-1) = 50
Check the assigned value
StaffName As String * 30
Addr(1 To 2) As String
Age As Integer
End Type
Sub OneDArrayDemo2()
Declare a 50-elements array of custom data types
With cusStaff(1)
.StaffName = Richard
.Addr(1) = 1, Wall Street
.Addr(2) = New York
.Age = 35
End With
Multidimensional arrays
A multidimensional array can be two, three, or more dimensions. The way to access each
element in a multi-dimensional array is by using the array name and the indexes of its
respective dimensions.
To check the lower and upper indexes for each dimension of an array, the LBound and
UBound functions are used. The following two listings show examples of how to check
the indexes for two and three dimensional arrays, respectively:
Sub MultiDimArrayDemo1()
Declaring a 4-by-5 two-dimensional
array of integers
Dynamic arrays
If the number of elements in an array that you want to declare is only known at runtime,
you may declare it as a dynamic array without stating the upper index (and the lower
index), for example:
Dim a() As Integer
Dim b() As Integer
You can later use the ReDim keyword to tell VBA the number of elements in the array, for
example:
ReDim a(2 To x)
ReDim b(1 To x, -3 To y)
where x and y are the values that are only known at runtime.
ReDim can be used for any number of times to change the number of elements in an array.
When it is used, the existing values in the array are destroyed. If to preserve the values,
you can use ReDim Preserve, such as:
ReDim Preserve a(2 To x + 5)
ReDim Preserve b(1 To x, -3 To 8)
However, you can resize only the last dimension of a dynamic array and can change only
its upper index.
The following listing is an example of how a dynamic array is resized in a For-Next
structure while preserving the values in the array.
Sub DynamicArrayDemo1()
For i = 1 To 5
ReDim Preserve dynArry(1 To i)
dynArry(i) = i * 2
Next
Declaring procedures
Declaring a procedure is to name the procedure and to specify its characteristics, such as
the data type and the scope of accessibility.
The syntax for a Function procedure:
Function Name ([ArgumentsList]) [As Type]
[statement(s)]
[Name = expression]
[Exit Function]
[statement(s)]
[Name = expression]
End Function
The syntax for a Sub procedure:
Sub Name ([ArgumentsList])
[statement(s)]
[Exit Sub]
[statement(s)]
End Sub
Name is the name of a procedure. The rules for naming procedures are the same as the
ones in naming arguments in the procedures, constants, and variables. A valid name must
begin with a letter. It can contain digits and underscore characters (_), but cannot
contain spaces, arithmetic operator symbols, punctuation marks, other special characters
Scope of procedures
A procedure can be called by procedures in any modules or only by procedures in the
module that stores the procedure. Its scope of accessibility (that is, from where it can be
called) depends on how (by using either the Public or Private keyword) it is declared, as
shown in the following table.
An example of how a procedure is
declared
Can be called
by
Function Power3(x As Double) As Double
Private Sub UpdateImage()
Procedures in
the module that
Private Function Power3(x As Double) As stores the
procedure
Double
A procedure declared without explicitly using the Public keyword is public by default.
If a public procedure is stored in a standard VBA module, it can be called by procedures
in any modules using the Call keyword, for example Call UpdateImage. If it is a Function
procedure, it can also be used as a worksheet function, just like other Excel built-in
worksheet functions.
A public Sub procedure in a standard VBA module can be executed in one of the
following ways:
Use the Macro dialog box. See Exercise 2-1.
Press the shortcut key combination that is assigned to the procedure. See Exercise
2-2.
In VBE, press F5 to run it.
Call it from the Immediate window. For example, to execute a Sub procedure
named CreateAlternateColorBanding, enter the following statement in the
Immediate window:
Call CreateAlternateColorBanding
Or
Application.Run CreateAlternateColorBanding
Call it by a procedure in other module. The way to call is the same as the one from
the Immediate window. For example,
Call CreateAlternateColorBanding
Or
Application.Run CreateAlternateColorBanding
Click a command button. If the command button is a form control, the Assign
Macro dialog box is automatically displayed after you draw the button on a
worksheet. In the dialog box, you can assign a Sub procedure to the button. If the
command button is an ActiveX control, please consult the topic A simple event
handler: CommandButton1_Click() in Chapter 2.
A public Function procedure in a standard VBA module can be executed in one of the
following ways:
Use it as a worksheet function. See Exercise 2-5.
Call it from the Immediate window. See Exercise 2-6.
Call it by a procedure in other module, as if it is a VBA built-in functions. See
Exercise 2-7.
If a public procedure is in a non-standard VBA module (such as a sheet or workbook
module), it can be called by procedures in any modules using the Call keyword and the
name of the module that stores the procedure, for example Call Sheet1.UpdateImage. If it
is a Function procedure, it cannot be used as a worksheet function.
A public Sub procedure either in a standard or non-standard VBA module can be executed
in the same ways, with one exception. In a statement calling a procedure in non-standard
module, the procedure name must be preceded by the module name, for example:
Call Sheet1.CreateAlternateColorBanding
Or
Application.Run Sheet1.CreateAlternateColorBanding
Often, when you want a procedure to be only accessible by the procedures in the module
storing the procedure, you declare it as a private procedure. However, VBA provides a
way to call a private procedure from other module. Since the way distracts the main
purpose of declaring a procedure private, it is only discussed later in Chapter 4 under the
topic Calling a private procedure from other module.
Literally there are countless of Function and Sub procedures. In the following discussion,
you will see some sample functions: from a function with no argument to a function with
an arbitrary number of arguments, from a function that returns a single value to a function
that returns an array of values, and functions with optional arguments. The sample
functions provide you the programming syntax on how to write those functions.
The discussion on the sample Function procedures applies also to Sub procedures, with
the only difference that Sub procedures do not return a value or an array of values.
ThisFilePath = ActiveWorkbook.Path
End Function
Exercise 3-2: Using a custom function as a worksheet function
As mentioned earlier, to use a custom function as a worksheet function, the function must
be stored in a standard VBA module and declared as public. To use the custom function
ThisFilePath as a worksheet function, execute the following steps:
1. Start a blank workbook, or open an existing workbook.
2. Press Alt+F11 to activate VBE.
3. Insert a new or use an existing standard VBA module.
4. Enter the VBA code for the custom function in the code window of the module.
5. Press Alt+F11 to activate Excel.
6. Save the workbook as a macro-enabled XLSM file in Excel 2010 2016 or XLM
file in Excel 2007.
7. Select any cell in a worksheet of the newly saved workbook and enter the
FileNameOnly = Mid(FullName, _
InStrRev(FullName, \) + 1)
End Function
This function can be used as a worksheet function and can be called by a procedure in any
module. To test the function, consult Exercises 3-2 and 3-3 above.
string and provides an option to a user whether the search is case-sensitive or caseinsensitive. The default value for the optional argument is vbTextCompare, which is
explicitly stated in the argument list of the function.
Function CountRepeat(MyString As String, _
enable the Auto List Members option in the Editor tab of the VBE Options dialog
box.
4. Use the up- and down-arrow keys and the Tab key to select an item in the list. For
example, the following statement returns 2:
? CountRepeat(abc Bb,b,vbBinaryCompare)
Exercise 3-5: Using a custom function (with a built-in constant) as a worksheet function
After storing the CountRepeat function in a standard VBA module, execute the following
steps to use the function in a worksheet formula:
1. Enter the following formula into any cell:
=CountRepeat(abc Bb,b)
It returns 3 correctly since the search of b in abc Bb is case-insensitive.
2. Enter the following formula into any cell:
=CountRepeat(abc Bb,b,vbBinaryCompare)
It returns an error because Excel does not recognize the VBA built-in constant:
vbBinaryCompare.
3. Use Object Browser to check the value of the built-in constant, or simply type the
following statement in the Immediate window to find out its value.
? vbBinaryCompare
It returns 0.
4. Enter the following formula into any cell:
=CountRepeat(abc Bb,b,0)
It then returns 2 correctly since the search of b in abc Bb is case-sensitive.
5. If cell A1 contains the text abc Bb, and cell A2 contains the text b, you may
test the function by entering the following formula into any other cells:
=CountRepeat(A1,A2,0)
It returns 2 correctly.
When a custom function has several arguments and it is used as a worksheet function, to
remember what to enter for each of these arguments is not easy. You may then press
Ctrl+Shift+A after typing an equal sign and the functions name into a cell (for example,
=CountRepeat) to display the names of the arguments.
The following shows a fictitious function with two optional arguments. Even though it is
fictitious, but at least it shows how an argument list of a function with any number of
optional arguments looks like.
Function AddAllDemo(arg1 As Long, _
In a worksheet,
enter the following
formula into a cell
Return
value
=AddAllDemo(5,6,7) 18
=AddAllDemo(5,6)
21
=AddAllDemo(5,,7)
12
12
A function can take not only single values, but also an array of values and arrays of values
as its arguments. Arrays are always passed by reference (ByRef). They cannot be passed
by value (ByVal).
Consider a function that takes only an array of values as its argument. In declaring the
function, there is no way to state the dimension of the array argument, for example:
Function MyArrayFunction(Arry() As Double)
End Function
However, you can restrict the dimension of the array when working with the VBA code in
the function. The table below shows how to restrict the dimension of an array argument to
one and two, and how to allow the array argument to accept an array of any dimensions.
A function with a one-dimensional array argument
Function SumAllArray1D(Arry() As Double) As Double
Dim i As Long
SumAllArray1D = 0
For i = LBound(Arry) To UBound(Arry)
SumAllArray1D = SumAllArray1D + Arry(i)
Next i
End Function
A function with a two-dimensional array argument
Function SumAllArray2D(Arry() As Double) As Double
End Function
A function with an array argument of arbitrary
dimensions
Function SumAllArrayMD(Arry() As Double) As Double
End Function
The first two arguments in the procedures argument list are required arguments: one is
passed by reference, and the other is passed by value.
The third argument with the ParamArray keyword is the one that enables the function to
take literally an array of an infinite number of arguments. It must be defined as an array of
variants and always be the last argument in the procedures argument list. It cannot be
used with the ByVal, ByRef, and Optional keywords.
The following SimpleSum1 function literally can take an infinite list of numbers in its
argument list.
Function SimpleSum1(ParamArray ArgList()) As Double
Dim i As Long
For i = 0 To UBound(ArgList)
SimpleSum1 = SimpleSum1 + ArgList(i)
Next
End Function
Note: LBound of ArgList() is always 0, regardless of the Option Base statement.
Alternatively, SimpleSum1 can be rewritten as below:
Function SimpleSum2(ParamArray ArgList()) As Double
Dim Item
For Each Item In ArgList
SimpleSum2 = SimpleSum2 + item
Next
End Function
An argument that passed to the SimpleSum1 and SimpleSum2 functions can be a number,
a number in a cell, or a number returned by a function.
Exercise 3-6: Using SimpleSum1 and SimpleSum2 as worksheet functions
After storing the SimpleSum1 and SimpleSum2 functions in a standard VBA module,
execute the following steps to use the functions as worksheet functions:
Next cel
Case Else
SimpleSum3 = SimpleSum3 + item
End Select
Next item
End Function
The TypeName function is used to determine the data type of the argument in the
argument list of the SimpleSum3 function.
Exercise 3-7: Using SimpleSum3 as a worksheet function
After storing the SimpleSum3 function in a standard VBA module, execute the following
steps to use the function in a worksheet formula:
1. Enter a few numbers separately into a few ranges of cells, for example the ranges
B1:B3 and B5:B7.
2. In any other cell, enter the following formula:
=SimpleSum3(3,SQRT(4),B1:B3,B5:D8)
It returns the sum of 3, 2, and the numeric values in the ranges B1:B3 and B5:D8.
For example, after storing the MySplit function in a standard VBA module, execute the
following steps:
1. Enter the following statement in the Immediate window
Range(A22:L22).FormulaArray = =MySplit(Hello World!)
2. Press Alt+F11 to activate Excel and see the result.
The next function ReturnArryDemo1 returns a 3-by-4 two-dimensional array:
Function ReturnArryDemo1() As Long()
3. Select another range that is larger than 3-by-4 cells, for example the range E25:I29.
4. Type the following array formula into the formula bar and press Ctrl+Shift+Enter
(not just Enter):
=ReturnArryDemo1()
The function not only returns numbers into the selected cells, but also fills out the
unused cells with #N/A errors.
You can then modify ReturnArryDemo1 to fill out the unused cells either with empty
characters or numbers. The following ReturnArryDemo2 function discusses the latter: to
fill out with numbers.
Function ReturnArryDemo2() As Long()
End Function
The VBA code in the ReturnArryDemo2 function first determines the size of a selected
range. Then, the dimensions of the array (that to be returned) is resized according to the
size of the selected range.
Debugging
Debugging is a process of finding and fixing errors in program code. The following is a
typical way of using the debugger to step through the code and identify errors:
1. Add breakpoints at particular lines of code, where you suspect errors, by clicking
at the grey left margin of the code window.
2. Press F5 to execute the VBA code.
VBE executes the code until the first breakpoint is met, putting the code into break
mode. The particular line of code at the breakpoint is not executed yet.
3. Choose one of the three operations at the breakpoint:
Operation
Shortcut
Action of the debugger
key
Continue
F5
Step Into
F8
Step Over
The operations listed in the table above can alternatively be accessed from the
Debug menu on the menu bar.
4. As you step through the code to identify possible errors, you can hover the mouse
pointer over any variable to examine its current value. If VBE does not display the
value, enable the Auto Data Tips option in the Editor tab of the VBE Options dialog
box. (Choose Tools | Options from the menu bar to display the Options dialog box.)
Alternatively, you may use the Immediate window to check the current value of a variable
when the code is in break mode. For example, enter the following statement in the
Immediate window:
? myVariable
In addition, you may use the Locals window and the Watch window (which are the topics
to be discussed next) to monitor the values of variables when debugging your VBA code.
Locals window
The Locals window allows you to observe the current values of all variables in a
procedure that is currently being executed. In VBE, choose View | Locals Window from
the menu bar to display the Locals window. Only when the code is in break mode, the
current values of all variables are displayed. Otherwise, the Locals window is empty.
Watch window
The Watch window allows you to put your VBA code into break mode when certain
condition is met. The condition is based on the value of an expression or a variable that
you set in the Watch window.
To add a variable as a watch to the Watch window, execute the following steps:
1. Right-click any occurrence of the variable, for example a variable named Sum, in
the code window.
2. Choose Add Watch from the shortcut menu to display the Add Watch dialog box.
The Expression box automatically inserts the name of the variable: Sum, in this
case.
3. In the Watch Type group, select one of the three watch types:
Watch Expression: The Watch window simply watches the expression
without stopping code execution. The value of the expression is displayed in
the Watch window only when VBE is in break mode.
Break When Value Is True: Your VBA code is put into break mode when the
value of the watched expression is True. If necessary, you may then change
the watched expression and its watch type.
Break When Value Changes: Your VBA code is put into break mode when
the value of the watched expression changes. If necessary, you may then
change the watched expression and its watch type.
4. Click OK to accept other default settings.
Only when VBE is in break mode, the current values of all watched expressions are
displayed. Otherwise, the values are out of context.
To edit (or delete) a watch, right-click the watch in the Watch window and choose Edit
Watch (or Delete Watch). If the Watch window is not visible, choose View | Watch
Window from the menu bar to display the window.
Call stack
The call stack lists all procedures that are currently running, with the most current
procedure at the top of the list. When VBE is in break mode, choose View | Call Stack
from the menu bar or press Ctrl+L to display the Call Stack dialog box. The dialog box
can only be displayed when there is at least one procedure in break mode.
Debug.Print Sum
Debug.Assert Sum <> 10
Next j
Next i
End Sub
6. Press Ctrl+G to display the Immediate window.
7. Choose View | Locals Window from the menu bar to display the Locals window.
8. Execute the following steps to add two watches: k changes and Sum = 3 is True.
a) Right-click any occurrence of the k variable in the code window.
b) Choose Add Watch from the shortcut menu to display the Add Watch dialog
box.
c) Type k into the Expression box.
d) In the Watch Type group, select the option Break When Value Changes.
e) Click OK to accept other default settings.
f) Right-click any occurrence of the Sum variable in the code window.
g) Choose Add Watch from the shortcut menu to display the Add Watch dialog
box.
h) Type Sum = 3 into the Expression box.
i) In the Watch Type group, select the option Break When Value Is True.
j) Click OK to accept other default settings.
9. Resize the Immediate, Locals, Watch, and code windows, if needed, so that you
can see all of them.
10. Click anywhere within the DebugDemo procedure to activate it and press F5 to run
it.
The VBA code is put into its first break mode when k changes from 0 to 1. Observe
the changes in the Locals and Watch windows.
11. Press F5 to continue the code execution.
The code is then in its second break mode when the expression Sum = 3 is True.
Observe the changes in the Locals and Watch windows.
The Debug.Print Sum statement of displaying the value of Sum (in this case, 3) in
Immediate window has not been executed yet. Hence, it is not shown in the
Immediate window.
12. Press F5 to continue the code execution.
VBE enters into break mode again when the condition (Sum <> 10) in the
Debug.Assert statement is False. Observe the value of Sum in the Locals window,
which is 10.
An alternative to the Debug.Assert Sum <> 10 statement is to add the Sum variable
as a watch to the Watch window: with the expression in the Expression box entered
as Sum = 10 and with its watch type selected Break When Value Is True.
13. Press Ctrl+L to the display the Call Stack dialog box.
Choose one of the two procedures in the list and click the Show button to jump to
the point of execution in the chosen procedure.
14. Press F5 a few more times to continue the code execution while observing the
changes in the Locals, Watch, and Immediate windows until the code execution
ends.
You can see that the VBA code is put into break mode whenever the k variable
changes, the expression Sum = 3 is True, or the value of the variable Sum is 10.
In a nutshell, you have seen four debugging tools to put VBE into break mode:
Stepping through the VBA code by using the debugger
Setting breakpoints in the VBA code
Adding watches to the Watch window
Inserting the Debug.Assert statements in the VBA code
When VBE is in break mode, the current values of variables can then be examined.
Other than as a debugging tool, the MsgBox function is also useful to get a decisive
response from a user. For example, if to let a user decide whether to continue the code
execution, you may display Yes and No buttons on the message box, and subsequently
handle the decision made by the user. The following block of statements shows a fictitious
example, where Sum is a variable:
If Sum = 10 Then _
Error handling
Without error handlers, any runtime error that occurs is fatal; that is, an error message is
displayed and execution stops abruptly. Rather than letting users helplessly facing error
messages, it is a good practice to trap errors and take appropriate actions, such as
displaying a more helpful message, in your error-handling code.
You can enable an error handler by using either the On Error Resume Next statement or
the On Error GoTo line statement. An error handler is enabled whenever the On Error
statement of the error handler is executed.
To disable error handling and let VBA handle errors, the On Error GoTo 0 statement is
executed. Table below briefly explains the role of these On Error statements:
On Error statement
Description
On Error Resume
Next
To ignore any runtime errors that occur and to continue with the next
statement. However, you might then use the Err object to determine
the next cause of action.
On Error GoTo 0
To allow error handlers in your VBA code to work, make sure that you have enabled the
Break on Unhandled Errors option in the General tab of the VBE Options dialog box.
(Choose Tools | Options from the menu bar to display the Options dialog box.)
To understand the discussion on error handlers later in this section, execute the following
steps:
1. Enter the Sub procedures listed in this section into a VBA module.
2. Press F8 to step through the code in those procedures.
3. Observe the output in the Immediate window and follow the flow of control,
especially when runtime errors occur.
no error handler
Debug.Print 1 / 0
Debug.Print other code not executed
End Sub
A general practice is to end an On Error Resume Next statement with an On Error GoTo 0
statement. Even without the On Error GoTo 0 statement, all error handlers are
automatically disabled when a procedure is exited.
Debug.Print 1 / 0
Debug.Print 1 executed
On Error GoTo 0
Debug.Print 1 / 0 fatal error
Exit Sub
err1:
error must have been occurred. Otherwise, an execution of the statement generates a
runtime error with an error message of Resume without error.
When a Resume statement is executed, VBE resumes execution at certain line of code in
the procedure, at which it depends on one of the following forms of the Resume statement.
Statement
Description
Resume
Resume Next
Resume line
When a Resume statement is executed, the current error handler is deactivated (but not
disabled). If a runtime error then occurs, the last enabled handler will be activated.
In the Sample4aInfiniteLoop procedure below, when the division-by-zero error occurs,
execution jumps to the line of code labeled err1. When the Resume statement is executed,
it resumes execution at the division-by-zero statement. Hence, the division-by-zero error
occurs again, On Error Goto err1 is activated again, and execution jumps to the line
labeled err1. Hence, the Sub procedure loops forever. The discussion here is for the
understanding of the flow of control when using the Resume statement. Please consult the
VBA Help system (by searching the word Resume) for a working example on how the
statement can possibly be used to rectify the cause of an expected runtime error.
Sub Sample4aInfiniteLoop()
Resuming execution at the line of code
that caused an error (without rectifying
the cause in the error-handling routine)
forms an infinite loop
Debug.Print 1 / 0
Exit Sub not executed
err1:
err1:
Debug.Print 1 / 0
Debug.Print 2 executed
End Sub
Overcoming fatal errors with a called Sub procedure
An alternative to handling errors gracefully in an error-handling routine, without using the
Resume statement, is to use a called procedure in the routine because any On Error
statement in a calling procedure will become inactive when another procedure is called.
The following SampleAsIn4c and SampleAsIn4d procedures show the alternatives to the
Sample4c and Sample4d procedures, respectively.
Sub SampleAsIn4c()
An alternative to Sample4c by using
a called procedure
Call GotoErr2Sub
End Sub
Private Sub GotoErr2Sub()
Other than the tools discussed in Chapter 1 and some tips discussed along the way in
previous chapters, below are some other tips on VBA programming for beginners.
with
an
0.031
The listing below is an example of VBA code that works with a range of cells.
Sub WorkingWithRange()
To count the number of numbers that are
divisible by 4 in a range of 50,000 cells.
Dim r As Long, c As Long
Dim rN As Long, cN As Long
Dim cnt As Long
Dim StartTimer As Date, EndTimer As Date
StartTimer = Timer
rN = 500: cN = 100: cnt = 0
For r = 1 To rN
For c = 1 To cN
If Sheets(1).Cells(r, c) Mod 4 = 0 _
StartTimer = Timer
rN = 500: cN = 100: cnt = 0
ReDim x(rN, cN)
Sheets(1).Activate
x = Range(A1).Resize(rN, cN)
For r = 1 To rN
For c = 1 To cN
If x(r, c) Mod 4 = 0 Then _
cnt = cnt + 1
Next c
Next r
EndTimer = Timer
Debug.Print cnt
Debug.Print EndTimer - StartTimer
End Sub
ScrnU = .ScreenUpdating
DispA = .DisplayAlerts
Evnt = .EnableEvents
Calc = .Calculation
End With
Disable them before the execution begins
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Here runs your code
Restore the initial settings
before the execution ends
With Application
.ScreenUpdating = ScrnU
.DisplayAlerts = DispA
.EnableEvents = Evnt
.Calculation = Calc
End With
Sub SumSelectedRange1()
Sum numbers in a selected range
If the SumSelectedRange2 procedure is executed for a worksheet where cell A1 and cell
XFD1048576 are used, then there is no difference in term of execution between
SumSelectedRange1 and SumSelectedRange2 (if the entire worksheet selected by a user
before execution). Nevertheless, in very rare cases, only cell A1 (or any cells near cell A1)
and cell XFD1048576 (or any cells near the last column XFD and the last row 1048576)
are used, but in between these cells mostly unused.
Another way to improve the execution time of SumSelectedRange1 is to deal with only
those cells with numbers. VBA provides a quick way to identify those cells: the
SpecialCells method, as shown in the SumSelectedRange3 procedure below.
Sub SumSelectedRange3()
Sum numbers in a selected range
Only working with numbers
Dealing with the situation when Auto List Members does not
work
In certain circumstances, even you have enabled the Auto List Members option in the
Editor tab of the VBE Options dialog box, typing the name of an object followed by a dot
does not display a list of members of the object. The following code demonstrates one of
those circumstances:
Worksheets(1).
A list of members of the Worksheet object is not displayed after the dot.
Note: In the above code, Worksheets is a container (also known as a collection) object. It
contains a collection of objects of the same type. A container object is usually the plural
form of objects it contains. An object in the container can be accessed either by an index
or the name of the object.
To display a list of member of an object, define an object variable for that object and then
type the object variable followed by a dot.
The following code demonstrates the idea for the Worksheet object, and in general it can
be any object:
Sub WithAutoListDemo()
Dim ws as Worksheet
ws.
End Sub
A list of members of the Worksheet object is displayed after the dot.