VBA-Excel Manual FunctionX PDF
VBA-Excel Manual FunctionX PDF
Introduction
When Microsoft Excel opens, it displays an interface divided in various sections. The top section
displays the title bar which starts on the left side with the Office Button
mouse on it, a tool tip would appear:
As you can see, the menu of the Office Button allows you to perform the routine Windows
operations of a regular application, including creating a new document, opening an existing file, or
saving a document, etc. If you right-click the office button, you would get a short menu:
http://www.functionx.com/vbaexcel/Lesson01.htm
few buttons. If you right-click the Quick Access toolbar, a menu would appear:
To hide the Quick Access toolbar, you can right-click it and click Remove Quick Access Toolbar. If
you position the mouse on a button, a tool tip would appear.
In the beginning, the Quick Access toolbar displays only three buttons: Save, Undo, and Redo. If
you want more buttons than that, you can right-click the Quick Access toolbar and click Customize
Quick Access Toolbar... This would display the Excel Options dialog box:
To add a button to the Quick Access toolbar, on the left list of Add, click an option and click Add.
After making the selections, click OK.
To remove a button from the Quick Access toolbar, right-click it on the Quick Access toolbar and
click Remove From Quick Access Toolbar.
The role of this button is to manage some aspects of the top section of the Microsoft Excel
interface, including deciding what buttons to display on the Quick Access toolbar. For example,
instead of using the Customize Quick Access Toolbar menu item as we saw previously, you can
click an option from that menu and its corresponding button would be added to the Quick Access
http://www.functionx.com/vbaexcel/Lesson01.htm
toolbar. If the options on the menu are nor enough, you can click either Customize Quick Access
Toolbar or More Commands... This would open the Excel Options dialog box.
The main or middle area of the top section displays the name of the application: Microsoft Excel.
You can right-click the title bar to display a menu that is managed by the operating system.
On the right side of the title bar, there are three system buttons that allow you to minimize,
maximize, restore, or close Microsoft Access.
Under the title bar, there is another bar with a Help button on the right side.
The Ribbon
Introduction
Under the title bar, Microsoft Excel displays the Ribbon:
By default, the Ribbon displays completely in the top section of Microsoft Excel under the title bar.
One option is to show it the way the main menu appeared in previous versions of Microsoft Excel.
To do this:
Right-click the Office Button, the Quick Access toolbar, or the Ribbon itself, and click Minimize
the Ribbon
Click or right-click the button on the right side of the Quick Access toolbar:
http://www.functionx.com/vbaexcel/Lesson01.htm
To put them back to the default locations, right-click the Office Button, the Quick Access toolbar,
or the Ribbon, and click Show Quick Access Toolbar Above the Ribbon.
To access a tab, you can press its corresponding letter on the keyboard. For example, when
the access keys display, if you press Home, the Home tab would display
If your mouse has a wheel, you can position the mouse anywhere on the ribbon, and role the
wheel (on the mouse). If you role the wheel down, the next tab on the right side would be
selected. If you role the wheel up, the previous tab on the left side would be selected. You can
keep rolling the wheel until the desired tab is selected
To identify each tab of the Ribbon, we will refer to them by their names.
You can also use context sensitive help in some cases to get information about an item.
You can add a button from a section of the Ribbon to the Quick Access toolbar. To do that,
right-click the button on the Ribbon and click Add to Quick Access Toolbar:
http://www.functionx.com/vbaexcel/Lesson01.htm
Remember that, to remove a button from the Quick Access toolbar, you can right-click it on the
Quick Access toolbar and click Remove From Quick Access Toolbar.
That button is used to display an intermediary dialog box for some actions.
In this case, when you need to access an object, you can still click it or click its arrow. If the item
is supposed to have many objects, a new window may appear and display those objects:
http://www.functionx.com/vbaexcel/Lesson01.htm
From this:
To this:
You can hide or show the Formula Bar anytime. To do this, on the Ribbon, click View. In the
Show/Hide section:
To hide the Formula Bar, remove the check mark on the Formula Bar check box
To show the Formula Bar, check the Formula Bar check box
http://www.functionx.com/vbaexcel/Lesson01.htm
The Cells
The main area of Microsoft Excel is made of cells. A cell is the intersection of a column and a row:
A cell is identified by its name and every cell has a name. By default, Microsoft Excel appends the
name of a row to the name of a column to identify a cell. Therefore, the top-left cell is named A1.
You can check the name of the cell in the Name Box.
http://www.functionx.com/vbaexcel/Lesson01.htm
In the lower right section of the main window, there is a horizontal scroll bar that allows you to
scroll left and right if your worksheet has more items than can be displayed all at once:
Sometimes the horizontal scroll bar will appear too long or too narrow for you. If you want, you
can narrow or enlarge it. To do this, click and drag the button on the left side of the horizontal
scroll bar:
By default, Microsoft Excel provides three worksheets to start with. You can work with any of
them and switch to another at any time by clicking its tab.
If you happen to use a lot of worksheets or the worksheet names are using too much space, which
would result in some worksheets being hidden under the horizontal scroll bar, you can use the
navigation buttons to move from one worksheet to another.
http://www.functionx.com/vbaexcel/Lesson01.htm
On the Quick Access Toolbar, you can click the Save button
You can click the Office Button and click Save
Two issues are important. Whenever you decide to save a file for the first time, you need to
provide a file name and a location. The file name helps the computer identify that particular file
and register it.
A file name can consist of up to 255 characters, you can include spaces and dashes in a name.
Although there are many characters you can use in a name (such as exclamation points, etc), try
to avoid fancy names. Give your file a name that is easily recognizable, a little explicit. For
example such names as Time Sheets, Employee's Time Sheets, GlobalEX First Invoice are explicit
enough. Like any file of the Microsoft Windows operating systems, a Microsoft Excel file has an
extension, which is .xls but you don't have to type it in the name.
The second important piece of information you should pay attention to when saving your file is
the location. The location is the drive and/or the folder where the file will be saved. By default,
Microsoft Excel saves its files in the My Documents folder. You can change that in the Save As
dialog box. Just click the arrow of the Save In combo box and select the folder you want.
Microsoft Excel allows you to save its files in a type of your choice. To save a file in another
format:
Press F12 or Shift + F12
You can click the Office Button and position the mouse on Save As and select the desired
option:
On the Quick Access Toolbar, you can click the Save button . Then, in the Save As dialog
box, click the arrow of the Save As Type combo box and select a format of your choice
There are other things you can do in the Save As dialog box:
http://www.functionx.com/vbaexcel/Lesson01.htm
10
11
Opening a File
The files you use could be created by you or someone else. They could be residing on your
computer, on another medium, or on a network. Once one of them is accessible, you can open it
in your application.
You can open a document either by double-clicking its icon in Windows Explorer, in My Computer,
from the Find Files Or Folders window, in My Network Places, or by locating it in the Open dialog
box. To access the open dialog box, on the main menu, click File -> Open... You can also click the
Open button on the Standard toolbar.
A shortcut to call the Open dialog box is Ctrl + O.
Files Properties
Every file has some characteristics, attributes, and features that make it unique; these are its
properties. You can access a file's properties from three main areas on the computer:
If the file is saved on the desktop and/or it has a shortcut on the desktop, if you open My
Computer, Windows Explorer, or the folder (as a window) where the file is stored, right-click
the file and click Properties. If the file were saved on the desktop, you would see only some of
its properties, the most you can do there is to assign a Read-Only attribute. In My Computer
and Windows Explorer, you will be able to change the file's properties.
Before opening a file or while in the Open dialog box, you can view some of the file's
properties although you won't be able to change them.
When the file is opened in Microsoft Excel, you can click the Office Button, position the mouse
on Prepare, and click Properties. This would display some of the most common attributes of
the file:
http://www.functionx.com/vbaexcel/Lesson01.htm
12
To change an item, you can click its text box and edit or replace the content. To get more
options, you can click the Document Properties button and click Advanced Properties...
A file's properties are used for various reasons. For example, you can find out how much size the
file is using, where it is located (the hosting drive and/or folder), who created the file, or who was
the last person to access or modify it. The Properties dialog box is also a good place to leave
messages to other users of the same file, about anything, whether you work as a team or you
simply want to make yourself and other people aware of a particular issue regarding the file.
Home
http://www.functionx.com/vbaexcel/Lesson01.htm
Next
13
From the Developer tab of the Ribbon, to launch Microsoft Visual Basic, you can click the Visual
Basic button.
http://www.functionx.com/vbaexcel/Lesson02.htm
14
4. Click OK
5. In the Code section of the Developer tab of the Ribbon, to launch Microsoft Visual Basic, click
Visual Basic:
http://www.functionx.com/vbaexcel/Lesson02.htm
15
To put the window back where it was previously, you can double-click its title bar.
The Properties Window shows the characteristics of an object that is selected. Like any other
window, to move the Properties window from its position, drag its title bar:
The main area of Microsoft Visual Basic uses a gray background. This area is gray because, in
reality, Microsoft Visual Basic is a multiple document interface (MDI) that can be used to display
various windows at the same time. At times, this gray area will be occupied with other windows.
Modules
A module is a blank window that resembles a piece of paper on which you write code. When you
use Microsoft Excel and work on a document, a default module is automatically allocated for it,
whether you use it or not. You can also create a module that is independent of any worksheet.
http://www.functionx.com/vbaexcel/Lesson02.htm
To create a module, on the main menu of Visual Basic, you can click Insert -> Module.
3. To return to Microsoft Excel, on the Standard toolbar of Visual Basic, click the View Microsoft
Excel button
4. To close Microsoft Visual Basic, on the main menu, click File -> Close and Return to Microsoft
Excel
http://www.functionx.com/vbaexcel/Lesson02.htm
16
Basic is a programming environment that uses a computer language. That language is called
Visual Basic for Applications (VBA). Although VBA is a language of its own, it is in reality derived
from the big Visual Basic computer language developed by Microsoft. In our lessons, we will learn
how to use VBA in Microsoft Excel.
To take advantage of the functionalities of the Microsoft Visual Basic environment, there are many
suggestions you can use or should follow. Because VBA is normal computer language, there are
various rules you must follow for the language to work.
Using VBA
In our lessons, we will use the word VBA sometimes but most of the time, we use the expression
"Visual Basic Language". When we use "Visual Basic language", we refer to a concept that is
recognized by all child languages of Visual Basic, including VBScript and VBA. When we will use
the word VBA, we refer to a concept that either is proper to VBA as a language and is not
necessarily applied to some other flavors of Visual Basic, or to the way the Visual Basic language
is used in Microsoft Excel. For example, the word String is used in all Visual Basic languages but
the word Variant is not used in the 2008 version of the Visual Basic language.
Macros
Creating a Macro
To launch Microsoft Visual Basic using the default installation of Microsoft Excel and launching
from a macro:
On the Ribbon, you can click View. In the Macros section, click the arrow under the Macros
button and click Record a Macro:
Click Developer. In the Code section, click the Record Macro button
In each case, the Record Macro dialog box would come up:
On the Record Macro dialog box, accept or enter a name for the macro. As an option, you can type
a description of the macro in the bottom text box. Once you are ready, click OK. This would bring
you to the document in Microsoft Excel where you can do what you want.
After doing what is necessary, to end the creation of the macro, on the Ribbon:
Click View. In the Macros section, click the the arrow of the Macros button and click Stop
Recording:
Click Developer. In the Code section, click the Stop Recording button
17
18
4. Click OK
5. In the document, whatever box is selected (don't click any), type =2
6. On the Formula Bar, click the Enter button
7. In the Code section of the Ribbon, click Stop Recording
To see the code of a macro, click its name and click Edit.
http://www.functionx.com/vbaexcel/Lesson02.htm
VBA in a Macro
We will try to reduce as much as possible the code that will be written for you. Still, there are
some lines and words we will keep or use but will ignore them for now. As we move on in our
lessons, you will understand what everyone of those words means. The code generated in the
above Practical Learning section was:
Sub Exercise()
ActiveCell.FormulaR1C1 = "=2"
End Sub
The first line of code has the word Sub. We will introduce it later on. Exercise1 is the name of the
macro we created. We will come back to names in a few sections in this lesson. We will also come
back to the role of parentheses. The section of code ends with the End Sub line. We will come
back to it when we study the procedures. For now, consider the Sub Exercise1() and End Sub
lines as the minimum requirements we need as this time, that we don't need to be concerned
with, but whose roles we can simply ignore at this time.
The most important line of our code, and the only line we are concerned with, is:
ActiveCell.FormulaR1C1 = "=2"
This line has three main sections: ActiveCell.FormulaR1C1, =, and "=2". For now, understand
that the ActiveCell.FormulaR1C1 expression means "whatever box is selected in the document".
The = sign is called the assignment operator. As its name indicates, the assignment operator is
used to assign something to another, to give a value to something, or more precisely to store
something somewhere.
The thing on the right side of = is called a value. Therefore, "=2" is a value. Based on this, the
expression ActiveCell.FormulaR1C1 = "=2" means "Assign the thing on the right side of = to
the thing on the left side of =." Another way to put it is, "Store the value on the right side of the
assignment operator to the selected box on the left side of the assignment operator." For now,
until indicated otherwise, consider that that's what that line of code means.
Using a Macro
After creating a macro, you can use it to see its result. This is also referred to as executing a
macro or running a macro.
To execute a macro, on the Ribbon:
Writing Code
Code Indentation
Indentation is a technique that allows you to write easily readable code. It consists of visually
showing the beginning and end of a section of code. Indentation consists of moving code to the
right side.
The easiest and most common way to apply indentation consists of pressing Tab before typing
your code. By default, one indentation, done when pressing Tab, corresponds to 4 characters. This
can be automatically set using the Tab Width text box of the Editor property page in the Options
dialog box. To change it, on the main menu of Microsoft Visual Basic, you can click Tools ->
Options and click the Editor tab:
http://www.functionx.com/vbaexcel/Lesson02.htm
19
20
If you don't want the pressing of Tab to be equivalent to 4 characters, change the value of the Tab
Width text box to a reasonable value and click OK. Otherwise, it is (strongly) suggested that you
keep to its default of 4 characters.
Comments
A comment is a piece of text in code that would not be considered when reading your code. As
such, a comment can be written any way you want.
In the Visual Basic language, the line that contains a comment can start with a single quote. Here
is an example:
This line will not be considered as part of the code
Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem,
Rem, or REM would not be read. Here is an example:
' This line will not be considered as part of the code
Rem I can write anything I want on this line
Comments are very useful and you are strongly suggested to use them regularly.
The code that was generated in our Practical Learning section contains a few lines of comment:
Sub Exercise1()
'
' Exercise1 Macro
'
'
ActiveCell.FormulaR1C1 = "=2"
End Sub
Previous
http://www.functionx.com/vbaexcel/Lesson02.htm
Next
21
Variables
Introduction
To use some values in code, you must first create them. The computer memory is made of small
storage areas used to hold the values of your application. When you use a value in your code,
the computer puts it in a storage area. When you need it, you let the computer know. The
machine "picks it up", brings it to you, and then you can use it as you see fit.
In the world of computer programming, a variable is a value you ask the computer to temporarily
store in its memory while the program is running.
4. Click OK
5. In the document, whatever box is selected (don't click any), type =2
6. On the Formula Bar, click the Enter button
7. In the Code section of the Ribbon, click Stop Recording
8. To open Microsoft Visual Basic, in the Code section of the Ribbon, click Macros
9. In the Macros dialog box, make sure Variables is selected and click Edit
Declaring a Variable
When writing your code, you can use any variable just by specifying its name. When you provide
this name, the computer directly reserves an area in memory for it. Microsoft Visual Basic allows
you to directly use any name for a variable as you see fit. Fortunately, to eliminate the possibility
of confusion, you can first let Visual Basic know that you will be using a variable.
In order to reserve that storage area, you have to let the computer know. Letting the computer
know is referred to as declaring the variable. To declare a variable, you start with the Dim word,
like this:
Dim
A variable must have a name. The name is written on the right side of the Dim word. There are
rules you should follow when naming your variables:
http://www.functionx.com/vbaexcel/Lesson03.htm
22
After starting with a letter or an underscore, the name can be made of letters, underscores,
and digits in any order
The name of a variable cannot have a period
The name of a variable can have up to 255 characters.
The name of a variable must be unique in the area where it is used
There are some words you should (must) not use to name your variables. Those words are
reserved for the VBA internal use. Therefore, those words are called keywords. Some of them are:
And (Bitwise) And
(Condition)
As
Boolean
ByRef
Byte
ByVal
Case
CBool
CByte
CDate
Call
CDbl
CInt
CLng
Const
CSng
CStr
Date
Dim
Do
Double
Each
Else
ElseIf
End
EndIf
Error
False
For
Function
Get
GoTo
If
Integer
Let
Lib
Long
Loop
Me
Mid
Mod
New
Next
Not
Nothing
Option
Or (Bitwise)
Or
(Condition)
Private
Public
ReDim
REM
Resume
Select
Set
Single
Static
Step
String
Sub
Then
To
True
Until
vbCrLf
vbTab
With
While
Xor
As mentioned already, to declare a variable, type Dim followed by a name. Here is an example:
Sub Exercise()
Dim Something
End Sub
Declaring a variable simply communicates to Visual Basic the name of that variable. You can still
use a mix of declared and not-declared variable. If you declare one variable and then start using
another variable with a similar but somewhat different name, Visual Basic would still consider that
you are using two variables. This can create a great deal of confusion because you may be trying
to use the same variable referred to twice. The solution to this possible confusion is to tell Visual
Basic that a variable cannot be used if it has not been primarily declared. To communicate this, on
top of each file you use in the Code Editor, type:
Option Explicit
This can also be done automatically for each file by checking the Require Variable Declaration
in the Options dialog box.
http://www.functionx.com/vbaexcel/Lesson03.htm
23
Value Assignment
We saw that when you declare a variable, the computer reserves a memory space for it but the
space is kept empty. After declaring the value, you can store a value you want in the memory
that was reserved for it.
To store a value in the memory reserved for a variable, you can assign a value to the variable. To
do this, type the name of the variable, followed by the assignment operator which is =, followed
by the value you want to store. Here is an example:
Sub Exercise()
Dim Value
Value = 9374
End Sub
As we will learn in the next few lessons, there are different types of values you will use in your
document. Also as we will see, the value you (decide to) store must be in accordance with the
type of memory that the computer had reserved for the variable.
After assigning a value to a variable, you can use that variable knowing the value it is currently
holding. At any time and when necessary, you can change the value held by a variable. That's
why it is called a variable (because its value can vary or change). To change the value held by a
variable, access the variable again and assign it the new desired value.
http://www.functionx.com/vbaexcel/Lesson03.htm
Type Characters
To make variable declaration a little faster and even convenient, you can replace the As DataType
expression with a special character that represents the intended data type. Such a character is
called a type character and it depends on the data type you intend to apply to a variable. When
used, the type character must be the last character of the name of the variable. We will see what
characters are available and when it can be applied.
Value Conversion
Every time the user enters a value in an application. That value is primarily considered as text.
This means that, if you want to use such a value in an expression or a calculation that expects a
specific value other than text, you must convert it from that text. Fortunately, Microsoft Visual
Basic provides an effective mechanism to convert a text value to one of the other values we will
see next.
To convert text to another value, there is a keyword adapted for the purpose and that depends on
the type of value you want to convert it to. We will mention each when necessary.
http://www.functionx.com/vbaexcel/Lesson03.htm
24
Byte
To declare a variable that would hold natural numbers that range from 0 to 255, use the Byte
data type. Here is an example:
Sub Exercise()
Dim StudentAge As Byte
End Sub
There is no type character for the Byte data type.
After declaring the variable, you can assign it a small positive number. Here is an example:
Sub Exercise()
Dim Value As Byte
Value = 246
End Sub
You can also use the number in hexadecimal format as long as the number is less than 255.
If you give either a negative value or a value higher to 255, when you attempt to access it, you
would receive an error:
To convert a value to a small number, you can use CByte(). The formula to use would be:
Number = CByte(Value to Convert to Byte)
When using CByte(), enter the value to convert in the parentheses.
http://www.functionx.com/vbaexcel/Lesson03.htm
25
6. In the Macros dialog box, make sure Exercise1 is selected and click Run
7. To return to Microsoft Visual Basic, in the Code section of the Ribbon, click Visual Basic
Integer
To declare a variable that would hold a number that ranges from -32768 to 32767, use the
Integer data type. Here is an example of declaring an integer variable:
Sub Exercise()
Dim Tracks As Integer
End Sub
Instead of using As Integer, you can use the % type character. Therefore, the above declaration
could be done as follows:
Sub Exercise()
Dim Tracks%
End Sub
After declaring the variable, you can assign the desired value to it. If you assign a value lower
than -32768 or higher than 32767, when you decide to use it, you would receive an error.
If you have a value that needs to be converted into a natural number, you can use CInt() using
the following formula:
Number = CInt(Value to Convert)
Between the parentheses of CInt(), enter the value, text, or expression that needs to be
converted.
Long
A long integer is a number that can be used for a variable involving greater numbers than
integers. To declare a variable that would hold such a large number, use the Long data type.
Here is an example:
Sub Exercise()
Dim Population As Long
End Sub
The type character for the Long data type is @. The above variable could be declared as:
Sub Exercise()
Dim Population@
End Sub
A Long variable can store a value between 2,147,483,648 and 2,147,483,647 (remember
that the commas are used to make the numbers easy to read; do not be used them in your code).
Therefore, after declaring a Long variable, you can assign it a number in that range.
To convert a value to a long integer, call CLng() using the following formula:
Number = CLng(Value to Convert)
To convert a value to long, enter it in the parentheses of CLng().
Decimal Variables
Single Precision
In computer programming, a decimal number is one that represents a fraction. Examples are 1.85
or 426.88. If you plan to use a variable that would that type of number but precision is not your
main concern, declare it using the Single data type. Here is an example:
Sub Exercise()
Dim Distance As Single
End Sub
The type character for the Single data type is !. Based on this, the above declaration could be
done as:
Sub Exercise()
Dim Distance!
End Sub
A Single variable can hold a number between 1.401298e45 and 3.402823e38. for negative
http://www.functionx.com/vbaexcel/Lesson03.htm
26
Double Precision
If you want to use a decimal number that requires a good deal of precision, declare a variable
using the Double data type. Here is an example of declaring a Double variable:
Sub Exercise()
Dim Distance As Double
End Sub
Instead of As Double, the type character you can use is #:
Sub Exercise()
Dim Distance#
End Sub
A Double variable can hold a number between 1.79769313486231e308 and
4.94065645841247e324 for negative values or between 4.94065645841247e324 and
1.79769313486231e308 for positive values.
To convert a value to double-precision, use CDbl() with the following formula:
Number = CDbl(Value to Convert)
In the parentheses of CDbl(), enter the value that needs to be converted.
6. To return to Microsoft Visual Basic, in the Code section of the Ribbon, click Visual Basic
A String
A string is a character or a combination of characters that constitute text of any kind and almost
any length. To declare a string variable, use the String data type. Here is an example:
Sub Exercise()
Dim CountryName As String
End Sub
The type character for the String data type is $. Therefore, the above declaration could be written
as:
Sub Exercise()
Dim CountryName$
End Sub
As mentioned already, after declaring a variable, you can assign a value to it. The value of a
string variable must be included inside of double-quotes. Here is an example:
http://www.functionx.com/vbaexcel/Lesson03.htm
27
28
Sub Exercise()
Dim CountryName As String
CountryName = "Brsil"
End Sub
If you have a value that is not primarily text and you want to convert it to a string, use CStr()
with the following formula:
CStr(Value To Convert to String)
In the parentheses of the CStr(), enter the value that you want to convert to string.
6. To return to Microsoft Visual Basic, in the Code section of the Ribbon, click Visual Basic
Currency Values
The Currency data type is used to deal with monetary values. Here is an example of declaring it:
Sub Exercise()
Dim StartingSalary As Currency
End Sub
Instead of using the As Currency expression, you can use @ as the type character to declare a
currency variable. Here is an example of declaring it:
Sub Exercise()
Dim StartingSalary@
End Sub
A variable declared with the Currency keyword can store a value between
922,337,203,685,477.5808 and 922,337,203,685,477.5807. Once again, keep in mind that the
commas here are used only to make the number easy to read. Don't use the commas in a number
in your code. Also, when assigning a value to a currency-based variable, do not use the currency
symbol.
Here is an example of assigning a currency number to a variable:
Sub Exercise()
Dim StartingSalary As Currency
StartingSalary = 66500
End Sub
If you want to convert a value to currency, use CCur() with the following formula:
Number = CCur(Value to Convert)
To perform this conversion, enter the value in the parentheses of CCur().
http://www.functionx.com/vbaexcel/Lesson03.htm
6. To return to Microsoft Visual Basic, in the Code section of the Ribbon, click Visual Basic
A Date
In Visual Basic, a Date data type can be used to store a date value. Therefore, to declare either a
date or a time variables, use the Date data type. Here is an example:
Sub Exercise()
Dim DateOfBirth As Date
End Sub
After declaring the variable, you can assign it a value. A date value must be included between two
# signs. Here is an example:
Sub Exercise()
Dim DateOfBirth As Date
DateOfBirth = #10/8/1988#
End Sub
There are various formats you can use for a date. We will deal with them in another lesson.
If you have a string or an expression that you want to convert to a date value, use CDate() based
on the following formula:
Result = CDate(Value to Convert)
In the parentheses of CDate(), enter the value that needs to be converted.
6. To return to Microsoft Visual Basic, in the Code section of the Ribbon, click Visual Basic
http://www.functionx.com/vbaexcel/Lesson03.htm
29
A Time
30
In Visual Basic, the Date data type can also be used to store a time value. Here is an example of
declaring a variable that can hold a time value:
Sub Exercise()
Dim ShiftTimeIn As Date
End Sub
After declaring the variable, to assign a value to it, include the value between two # signs. The
value follows different rules from a date.
To convert a value or an expression to time, use CDate().
Any-Type Variables
A Variant
So far, we declared variables knowing the types of values we wanted them to hold. VBA provides
a universal (or vague) data type you can use for any type of value. The Variant data type is used
to declare a variable whose type is not explicitly specified. This means that a Variant data type
can hold any type of value you want.
Here are examples of Variant-declared variables that hold different types of values:
Sub Exercise()
Dim FullName As Variant
Dim EmploymentStatus As Variant
Dim HourlySalary As Variant
Dim DateHired As Variant
FullName = "Patricia Katts"
EmploymentStatus = 2
HourlySalary = 35.65
DateHired = #6/22/2004#
End Sub
http://www.functionx.com/vbaexcel/Lesson03.htm
FirstName = "Patricia"
End Sub
31
You cannot use such a variable outside of its Sub Name and the End Sub lines.
Global Variables
A global variable is a variable declared outside of the Sub Name and the End Sub lines. Such a
variable is usually declared in the top section of the file. Here is an example:
Option Explicit
Dim LastName As String
Sub Exercise()
End Sub
After declaring a global variable, you can access it in the other areas of the file. Here is an
example:
Option Explicit
Dim LastName As String
Sub Exercise()
Dim FirstName As String
FirstName = "Patricia"
LastName = "Katts"
End Sub
Although we declared our global variable inside of the file where it was used, you can also declare
a global variable in a separate module to be able to use it in another module.
Private Variables
A variable is referred to as private if it can be accessed only by code from within the same file
(the same module) where it is used. To declare such a variable, instead of Dim, you use the
Private keyword. Here is an example:
Option Explicit
Private LastName As String
Sub Exercise()
Dim FirstName As String
FirstName = "Patricia"
LastName = "Katts"
End Sub
Remember that a private variable can be accessed by any code in the same module. In the next
lesson, we will learn how to create other sections of code.
Public Variables
A variable is referred to as public if it can be accessed by code either from within the same file
(the same module) where it is declared or from code outside its module. To declare a public
variable, instead of Dim, you use the Public keyword. Here is an example:
Option Explicit
Private LastName As String
Public FullName As String
Sub Exercise()
Dim FirstName As String
FirstName = "Patricia"
LastName = "Katts"
FullName = FirstName & " " & LastName
End Sub
http://www.functionx.com/vbaexcel/Lesson03.htm
As a reminder, a public variable is available to code inside and outside of its module. This means
that you can create a module, declare a public variable in it, and access that variable in another
file (module) where needed.
32
A private variable is available inside its module but not outside its module. If you declare a private
variable in a module and try accessing it in another module, you would receive an error:
Module 1:
Option Explicit
Private FullName As String
Module 2:
Option Explicit
Private LastName As String
Private FirstName As String
Sub Exercise()
FirstName = "Patricia"
LastName = "Katts"
FullName = FirstName & " " & LastName
ActiveCell.FormulaR1C1 = FullName
End Sub
This would produce:
Previous
http://www.functionx.com/vbaexcel/Lesson03.htm
Next
33
VBA Operators
Introduction
An operation is an action performed on one or more values either to modify one value or to
produce a new value by combining existing values. Therefore, an operation is performed using at
least one symbol and one value. The symbol used in an operation is called an operator. A
variable or a value involved in an operation is called an operand.
A unary operator is an operator that performs its operation on only one operand.
An operator is referred to as binary if it operates on two operands.
Dimensioning a Variable
When interacting with Microsoft Excel, you will be asked to provide a value. Sometimes, you will
be presented with a value to view or change. Besides the values you use in a spreadsheet, in the
previous lesson, we learned that we could also declare variables in code and assign values to
them.
In the previous lesson, we saw that we could use the Dim operator to declare a variable. Here
is an example:
Option Explicit
Sub Exercise()
Dim Value
End Sub
After declaring a variable like this, we saw that we could then use it as we saw fit.
If you plan to write a long piece of code, to make it easier to read, you may need to divide it in
various lines. To do this, you can use the line continuation operator represented by a white
space followed by an underscore.
To create a line continuation, put an empty space, then type the underscore, and continue your
code in the next line. Here is an example:
Sub _
Exercise()
End Sub
The Parentheses: ()
Parentheses are used in various circumstances. The parentheses in an operation help to create
sections in an operation. This regularly occurs when more than one operators are used in an
operation. Consider the following operation:
8 + 3 * 5
The result of this operation depends on whether you want to add 8 to 3 then multiply the result
by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to
specify which operation should be performed first in a multi-operator operation. In our example,
if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) * 5.
This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add the
result to 8, you would write 8 + (3 * 5). This would produce 23.
As you can see, results are different when parentheses are used on an operation that involves
various operators. This concept is based on a theory called operator precedence. This theory
manages which operation would execute before which one; but parentheses allow you to
completely control the sequence of these operations.
The Comma ,
The comma is used to separate variables used in a group. For example, a comma can be used to
delimit the names of variables that are declared on the same line. Here is an example:
Sub Exercise()
Dim FirstName As String, LastName As String, FullName As String
End Sub
Sub Exercise()
Dim FirstName As String, LastName As String, FullName As String
FirstName = "Valre"
ActiveCell.FormulaR1C1 = FirstName
End Sub
34
The & operator is used to append two strings or expressions. This is considered as concatenating
them. For example, it could allow you to concatenate a first name and a last name, producing a
full name. The general syntax of the concatenation operator is:
Value1 & Value2
In the same way, you can use as many & operators as you want between any two strings or
expressions. After concatenating the expressions or values, you can assign the result to another
variable or expression using the assignment operator. Here are examples:
Sub Exercise()
Dim FirstName As String, LastName As String, FullName As String
FirstName = "Valre"
LastName = "Edou"
FullName = FirstName & " " & LastName
End Sub
Arithmetic Operators
Positive Unary Operator: +
Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The
numbers on the left side of the 0 are referred to as negative while the numbers on the right
side of the rulers are considered positive:
-
-6
-5
-4
-3
-2
-1
0
-
-6
-5
-4
-3
-2
-1
A value on the right side of 0 is considered positive. To express that a number is positive, you
can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is
called a unary operator because it acts on only one operand.
The positive unary operator, when used, must be positioned on the left side of its operand,
never on the right side.
As a mathematical convention, when a value is positive, you don't need to express it with the +
operator. Just writing the number without any symbol signifies that the number is positive.
Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228,
90335. Because the value does not display a sign, it is referred as unsigned.
The Negative Operator -
As you can see on the above ruler, in order to express any number on the left side of 0, it must
be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value
accompanied by - is referred to as negative.
The - sign must be typed on the left side of the number it is used to negate.
Remember that if a number does not have a sign, it is considered positive. Therefore, whenever
a number is negative, it MUST have a - sign. In the same way, if you want to change a value
from positive to negative, you can just add a - sign to its left.
Addition +
The addition is performed with the + sign. It is used to add one value to another. Here is an
example:
Sub Exercise()
Dim Side#
Dim Perimeter#
http://www.functionx.com/vbaexcel/Lesson04.htm
35
Side# = 42.58
Perimeter# = Side# + Side# + Side# + Side#
End Sub
Besides arithmetic operations, the + symbol can also be used to concatenate strings, that is, to
add one string to another. This is done by appending one string at the end of another. Here is
an example:
Sub Exercise()
Dim FirstName$, LastName$, FullName$
FirstName$ = "Danielle"
LastName$ = "Kouma"
FullName$ = FirstName$ + " " + LastName$
ActiveCell.FormulaR1C1 = FullName$
End Sub
Multiplication *
The multiplication operation allows you to add a number to itself a certain number of times set
by another number. The multiplication operation is performed using the * sign. Here is an
example:
Sub Exercise()
Dim Side#
Dim Area#
Side# = 42.58
Area# = Side# * Side#
End Sub
Subtraction The subtraction operation is performed using the - sign. This operation produces the difference
of two or more numbers. It could also be used to display a number as a negative value. To
subtract 28 from 65, you express this with 65-28.
The subtraction can also be used to subtract the values of two values.
Integer Division \
Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division is
used to get the fraction of one number in terms of another. The Visual Basic language provides
two types of operations for the division. If you want the result of the operation to be a natural
number, called an integer, use the backlash operator "\" as the divisor. The formula to use is:
Value1 \ Value2
This operation can be performed on two types of valid numbers, with or without decimal parts.
After the operation, the result would be a natural number.
Decimal Division /
The second type of division results in a decimal number. It is performed with the forward slash
"/". Its formula is:
Value1 / Value2
After the operation is performed, the result is a decimal number.
Exponentiation ^
Exponentiation is the ability to raise a number to the power of another number. This operation
is performed using the ^ operator (Shift + 6). It uses the following formula:
yx
In Microsoft Visual Basic, this formula is written as:
y^x
and means the same thing. Either or both y and x can be values, variables, or expressions, but
they must carry valid values that can be evaluated. When the operation is performed, the value
of y is raised to the power of x.
Remainder: Mod
The division operation gives a result of a number with or without decimal values, which is fine
in some circumstances. Sometimes you will want to get the value remaining after a division
renders a natural result.
http://www.functionx.com/vbaexcel/Lesson04.htm
36
The remainder operation is performed with keyword Mod. Its formula is:
Value1 Mod Value2
The result of the operation can be used as you see fit or you can display it in a control or be
involved in another operation or expression.
Bit Manipulations
Introduction
From our introduction to variables, you may remember that the computer stores its
data in memory using small locations that look like boxes and each box contains a
bit of information. Because a bit can be represented only either as 1 or 0, we can
say that each box contains 1 or 0. Bit manipulation consists of changing the value
(1 or 0, or 0 or 1) in a box. As we will see in the next few operations, it is not just
about changing a value. It can involve reversing a value or kind of "moving" a box
from its current position to the next position.
The operations on bits are performed on 1s and 0s only. This means that any
number in decimal or hexadecimal format involved in a bit operation must be
converted to binary first.
You will almost never perform some of the operations we are going to review. You
will hardly perform some other operations. There is only one operation you will
perform sometimes: the OR operation.
"Reversing" a Bit
Remember that, at any time, a box (or chunk) in memory contains either 1 or 0:
Bit reversal consists of reversing the value of a bit. If the box contains 1, you can
reverse it to 0. If it contains 0, you can reverse it to 1. To support this operation,
the Visual Basic language provides the Not Operator.
As an example, consider the number 286. The decimal number 286 converted to
binary is 100011110. You can reverse each bit as follows:
286
Not 286
Bitwise Conjunction
Bitwise conjunction consists of adding the content of one box (a bit) to the content
of another box (a bit). To support the bitwise conjunction operation, the Visual
Basic language provides the And operator.
To perform the bit addition on two numbers, remember that they must be converted
to binary first. Then:
If a bit with value 0 is added to a bit with value 0, the result is 0
Bit0
Bit1
Bit1
Bit1
http://www.functionx.com/vbaexcel/Lesson04.htm
37
Bit1
As an example, consider the number 286 bit-added to 475. The decimal number
286 converted to binary is 100011110. The decimal number 4075 converted to
binary is 111111101011. Based on the above 4 points, we can add these two
numbers as follows:
286 0
4075 1
64
32
16
256
Number1 = 286
Number2 = 4075
Result = Number1 And Number2
ActiveCell.FormulaR1C1 = Result
End Sub
Bitwise Disjunction
Bitwise disjunction consists of disjoining one a bit from another bit. To support this
operation, the Visual Basic language provides the Or operator.
To perform a bitwise conjunction on two numbers, remember that they must be
converted to binary first. Then:
If a bit with value 0 is added to a bit with value 0, the result is 0
Bit0
Bit1
Bit0 Or Bit1
Bit1
Bit0 Or Bit1
Bit1
Bit0 Or Bit1
Bit1
Bit0 Or Bit1
As an example, consider the number 305 bit-disjoined to 2853. The decimal number
305 converted to binary is 100110001. The decimal number 2853 converted to
binary is 101100100101. Based on the above 4 points, we can disjoin these two
numbers as follows:
http://www.functionx.com/vbaexcel/Lesson04.htm
38
305 0
2853 1
305 Or 2853 1
39
2048
512 256
64
32
16
32
16
This means that 286 And 4075 = 2048 + 512 + 256 + 32 + 16 + 4 + 1 = 2869
This can also be programmatically calculated as follows:
Sub Exercise()
Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer
Number1 = 286
Number2 = 4075
Result = Number1 Or Number2
ActiveCell.FormulaR1C1 = Result
End Sub
Bitwise Exclusion
Bitwise exclusion consists of adding two bits with the following rules. To support
bitwise exclusion, the Visual Basic language provides an operator named Xor:
If both bits have the same value, the result is 0
Bit0
Bit1
Bit1
As an example, consider the number 618 bit-excluded from 2548. The decimal
number 618 converted to binary is 1001101010. The decimal number 2548
converted to binary is 100111110100. Based on the above 2 points, we can
bit-exclude these two numbers as follows:
618 0
2548 1
2048
64
32
16
16
This means that 286 And 4075 = 2048 + 512 + 256 + 128 + 16 + 8 + 4 + 2 =
2974
This can also be programmatically calculated as follows:
Sub Exercise()
Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer
Number1 = 286
Number2 = 4075
Result = Number1 Xor Number2
ActiveCell.FormulaR1C1 = Result
http://www.functionx.com/vbaexcel/Lesson04.htm
End Sub
Previous
40
http://www.functionx.com/vbaexcel/Lesson04.htm
Next
41
Introduction to Procedures
Procedures
A procedure is a section of code created to carry an assignment, separate from a spreadsheet,
whose action can be used to complement a spreasheet. You create the procedure by writing
code. One of the advantages of a procedure is that, once it exists, you can access it when
necessary and as many times as you want.
There are two categories of procedures you will use in your spreadsheets: those that are already
installed with Microsoft Excel and those you will create.
Introduction to Sub-Procedures
A sub procedure is an assignment that is carried but does not give back a result. To create a sub
procedure, start with the Sub keyword followed by a name (like everything else, a procedure
must have a name). The name of a procedure is always followed by parentheses. At the end of
the sub procedure, you must type End Sub. Therefore, the primary formula to create a sub
procedure is:
Sub ProcedureName()
End Sub
The name of a procedure should follow the same rules we learned to name the variables. In
addition:
If the procedure performs an action that can be represented with a verb, you can use that
verb to name it. Here are examples: show, display
To make the name of a procedure stand, you should start it in uppercase. Examples are Show,
Play, Dispose, Close
You should use explicit names that identify the purpose of the procedure. If a procedure would
be used as a result of another procedure or a control's event, reflect it on the name of the sub
procedure. Examples would be: afterupdate, longbefore.
If the name of a procedure is a combination of words, you should start each word in
uppercase. An example is AfterUpdate
The section between the Sub and the End Sub lines is referred to as the body of the procedure.
Here is an example:
Sub CreateCustomer()
End Sub
In the body of the procedure, you carry the assignment of the procedure. It is also said that you
define the procedure or you implement the procedure.
One of the actions you can in the body of a procedure consists of declaring a variable. There is no
restriction on the type of variable you can declare in a procedure. Here is an example:
http://www.functionx.com/vbaexcel/Lesson05.htm
42
Sub CreateCustomer()
Dim strFullName As String
End Sub
In the same way, you can declare as many variables as you need inside of a procedure. The
actions you perform inside of a procedure depend on what you are trying to accomplish. For
example, a procedure can simply be used to create a string. The above procedure can be changed
as follows:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
Introduction to Functions
Introduction
Like a sub procedure, a function is used to perform an assignment. The main difference between a
sub procedure and a function is that, after carrying its assignment, a function gives back a result.
http://www.functionx.com/vbaexcel/Lesson05.htm
We also say that a function "returns a value". To distinguish both, there is a different syntax you
use for a function.
Creating a Function
To create a function, you use the Function keyword followed by a name and parentheses. Unlike
a sub procedure, because a function returns a value, you must specify the type of value the
function will produce. To give this information, on the right side of the closing parenthesis, you
can type the As keyword, followed by a data type. To indicate where a function stops, type End
Function. Based on this, the minimum syntax used to create a function is:
AccessModifier Function FunctionName() As DataType
End Function
As seen for a sub procedure, a function can have an access modifier.
The Function keyword is required.
The name of a function follows the same rules and suggestions we reviewed for names of sub
procedures.
The As keyword may be required (in the next sections, we will review the alternatives to the As
DataType expression).
The DataType factor indicates the type of value that the function will return. If the function will
produce a word or a group of words, you can create it as String. The other data types are also
valid in the contexts we reviewed them in the previous lesson. Here is an example:
Function GetFullName() As String
End Function
Option Explicit
Function GetCustomerName() As String
End Function
Here is an example:
Function GetFullName$()
End Function
As mentioned for a sub procedure, the section between the Function and the End Function lines
is the body of the function. It is used to describe what the function does. As done on a sub
procedure, one of the actions you can perform in a function is to declare a (local) variable and use
it as you see fit. Here is an example:
Function CallMe() As String
Dim Salute As String
Salute = "You can call me Al"
End Function
http://www.functionx.com/vbaexcel/Lesson05.htm
43
LastName = "Katts"
44
Option Explicit
Function GetCustomerName() As String
GetCustomerName = "Paul Bertrand Yamaguchi"
End Function
2. To return to Microsoft Excel, on the Standard toolbar, click the View Microsoft Excel button
Calling a Function
As done for the sub procedure, in order to use a function in your program, you must call it. Like a
sub procedure, to call a function, you can simply type its name in the desired section of the
program. Here is an example:
Function CallMe() As String
Dim Salute As String
Salute = "You can call me Al"
CallMe = Salute
End Function
Sub Exercise()
CallMe
End Sub
When calling the function, you can optionally type the parentheses on the right side of its name.
The primary purpose of a function is to return a value. To better take advantage of such a value,
you can assign the name of a function to a variable in the section where you are calling the
function. Here is an example:
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = "Patricia"
LastName = "Katts"
GetFullName = LastName & ", " & FirstName
End Function
Sub Exercise()
Dim FullName$
FullName = GetFullName()
ActiveCell.FormulaR1C1 = FullName
End Sub
http://www.functionx.com/vbaexcel/Lesson05.htm
FirstName = "Patricia"
LastName = "Katts"
45
3. If you see GetCustomerName in the list, double-click it. Otherwise, complete it with
=GetCustomerName() and, on the Formula Bar, click the Enter button
http://www.functionx.com/vbaexcel/Lesson05.htm
Option Explicit
46
Introduction to Arguments
So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may
need an external value in order to carry its assignment. A value that is supplied to a
procedure is called an argument.
When creating a procedure that will use an external value, declare the argument that
represents that value between the parentheses of the procedure. For a sub procedure, the
syntax you use would be:
Sub ProcedureName(Argument)
End Sub
If you are creating a function, the syntax would be:
Function ProcedureName(Argument) As DataType
Function Sub
The argument must be declared as a normal variable, omitting the Dim keyword. Here is an
example that creates a function that takes a string as argument:
Function CalculatePayroll(strName As String) As Double
Function Sub
While a certain procedure can take one argument, another procedure can take more than
one argument. In this case, in the parentheses of the procedure, separate the arguments
with a comma. Here is an example of a sub procedure that takes two arguments:
Sub EvaluateInvoice(EmplName As String, HourlySalary As Currency)
End Sub
In the body of a procedure that takes one or more arguments, use the argument(s) as you
see fit as if they were locally declared variables. For example, you can involve them with
values inside of the procedure. You can also exclusively use the values of the arguments to
perform the assignment.
Option Explicit
Public Function CalculatePerimeter(Length As Double, _
Width As Double) As Double
Dim Perimeter As Double
Perimeter = (Length + Width) * 2
CalculatePerimeter = Perimeter
End Function
Public Function CalculateArea(Length As Double, Width As Double) As Double
Dim Area As Double
Area = Length * Width
CalculateArea = Area
End Function
http://www.functionx.com/vbaexcel/Lesson05.htm
argument, followed by =, and the value of the argument. If the procedure takes more than
one argument, separate them with commas. Here is an example:
Private Function GetFullName$(First As String, Last As String)
Dim FName As String
FName = First & Last
GetFullName = FName
End Function
Sub Exercise()
Dim FirstName As String, LastName As String
Dim FullName As String
FirstName = "Patricia "
LastName = "Katts"
FullName = GetFullName(FirstName, LastName)
ActiveCell.FormulaR1C1 = FullName
End Sub
As mentioned previously, you can also use the Call keyword to call a procedure.
When you call a procedure that takes more than one argument, you must provide the
values of the arguments in the order they are listed inside of the parentheses. Fortunately,
you don't have to. If you know the names of the arguments, you can type them in any
order and provide a value for each. To do this, in the parrentheses of the procedure you are
calling, type the name of the argument whose value you want to specify, followed by the :=
operator, and followed by the desired value for the argument. Here is an example:
Private Function GetFullName$(First As String, Last As String)
Dim FName As String
FName = First & Last
GetFullName = FName
End Function
Sub Exercise()
Dim FullName$
FullName$ = GetFullName(Last:="Roberts", First:="Alan ")
ActiveCell.FormulaR1C1 = FullName
End Sub
The above technique we have just seen for using the parentheses is valid for sub
procedures and functions. If the procedure you are calling is a sub, you can omit the
parentheses. If calling a sub procedure, after the name of the procedure, put an empty
space, followed by the name of the argument assigned the desired value. Here is an
example:
Private Sub ShowResult(ByVal Result As Double)
Result = 145.85
End Sub
Public Sub Exercise()
Dim Number As Double
ShowResult Number
End Sub
If the sub procedure is taking more than one argument, separate them with commas.
http://www.functionx.com/vbaexcel/Lesson05.htm
47
48
3. In the list of suggested functions, double-click CalculatePerimeter. If you don't see it,
complete the typing with =CalculatePerimeter(
4. After the opening parenthesis, type 48.26, 25.42 as the arguments, then type the
closing parenthesis ")"
6. Press Enter
7. Type =CalculateArea(48.26, 25.26) and press Enter
http://www.functionx.com/vbaexcel/Lesson05.htm
End Function
49
If you create a procedure that takes an argument by value and you have used the ByVal
keyword on the argument, when calling the procedure, you do not need to use the ByVal
keyword; just the name of the argument is enough, as done in the examples on arguments
so far. Here is an example:
Private Function GetFullName$(ByVal First As String, ByVal Last As String)
Dim FName As String
FName = First & Last
GetFullName$ = FName
End Function
Sub Exercise()
Dim FirstName As String, LastName As String
Dim FullName As String
FirstName = "Raymond "
LastName = "Kouma"
FullName = GetFullName(FirstName, LastName)
ActiveCell.FormulaR1C1 = FullName
End Sub
http://www.functionx.com/vbaexcel/Lesson05.htm
50
ShowResult Number
ActiveCell.FormulaR1C1 = Number
End Sub
When the Exercise() procedure starts, the Number variable is declared and its value is set
to 0. When the ShowResult variable is called, it assigns a value to the variable. Since the
variable is declared by reference, when the procedure exits, the variable comes back with
the new value it was given. As a result, when this code runs, the Number variable has a
new value.
Using this technique, you can pass as many arguments by reference and as many
arguments by value as you want. As you may guess already, this technique can be used to
make a sub procedure return a value, which a regular sub routine cannot do. Furthermore,
passing arguments by reference allows a procedure to return as many values as possible
while a regular function can return only one value.
Previous
Next
http://www.functionx.com/vbaexcel/Lesson05.htm
51
These characteristics are used to describe a house to somebody who wants to buy it. To get such
an object, you must first define the criteria that describe it. Here is an example:
House
[
Address
Type of House
Number of Bedrooms
Number of Bathrooms
Has Indoor Garage
The Living Room is Covered With Carpet
The Kitchen Has an Island Stove
]
This information is used to describe a house. Based on this, House is called a class. To actually
describe a real house, you must provide information for each of the above characteristics. Here is
an example:
House: Langston
[
Address: 6802 Leighton Ave
Type of House: Single Family
Number of Bedrooms: 4
Number of Bathrooms: 3
Has Indoor Garage: Yes
The Living Room is Covered With Carpet: Yes
The Kitchen Has an Island Stove: No
]
In this case, Langston is not a class anymore, it is a real house and is explicitly described.
Therefore, Langston is called an object. Based on this, a class is a technique used to provide the
criteria to define an object. An object is the result of a description based on a class.
http://www.functionx.com/vbaexcel/Lesson06.htm
52
In our example of a house, we used words to describe it. Examples are: Address, Type of House,
Number of Bedrooms, Number of Bathrooms. In computer programming, the characteristics used
to describe an object are referred to as its properties.
To display the characteristics of a Windows control, in Microsoft Excel:
You can right-click the control and click Properties
If the control is selected in the work area, in the Controls section of the Ribbon, click the
Properties button
Any of these two actions would display the Properties window for the control that was rightclicked:
The Properties window would stay on the screen of Microsoft Excel as long as you want. To show
the properties of another control, simply click it in the work area.
If you are working in Microsoft Visual Basic, to show the characteristics of a control, right-click it
and click Properties. This also would display the Properties window and show the characteristics of
the selected control. While the Properties window in Microsoft Excel floats and does not hold a
specific position, by default, in Microsoft Visual Basic, the Properties window is position on the
lower-left side.
You can move it by dragging its title bar.
http://www.functionx.com/vbaexcel/Lesson06.htm
have a House object named Langston and you want to ask it to protect its inside from outside
rain, you would type:
Langston.ProtectFromOutside()
This is also referred to as calling a method.
Default Arguments
We have mentioned that, when calling a method that takes an argument, you must supply a value
for the argument. There is an exception. Depending on how the method was created, it may be
configured to use its own value if you fail, forget, or choose not, to provide one. This is known as
the default argument. Not all methods follow this rule.
If a method that takes one argument has a default value for it, then you don't have to supply a
value when calling that method. Such an argument is considered optional.
If a method takes more than one argument, some argument(s) may have default values while
some others do not. The arguments that have default values can be used and you don't have to
supply them.
We will mention default arguments when we come to a method that takes some.
http://www.functionx.com/vbaexcel/Lesson06.htm
53
With
We have seen that you can use the name of an object to access its members. Here
is an example:
Camden.Address
Camden.TypeOfHouse
Camden.NumberOfBedrooms
Camden.NumberOfBathrooms
Camden.HasIndoorGarage
Instead of using the name of the object every time, you can start a section with the
With keyword followed by the name of the object. In another line, end the section
with the End With expression:
With Camden
End With
Between the With and the End With lines, to access a member of the class that the
object is built from, type a period followed by the desired member. This would be
done as follows:
With Camden
.Address
.TypeOfHouse
.NumberOfBedrooms
.NumberOfBathrooms
.HasIndoorGarage
End With
As you access a member, you can perform on it any action you judge necessary.
http://www.functionx.com/vbaexcel/Lesson06.htm
54
55
The Properties window allows you view or change a characteristic of the control. The
properties of an object can be changed when designing it or by writing code. The
time you are designing an application is referred to as design time. The time the
application (form) displays to the user is referred to as run time.
You can manipulate the characteristics of a control both at design and at run times.
This means that you can set some properties at design time and some others at run
time.
Previous
http://www.functionx.com/vbaexcel/Lesson06.htm
Next
56
Each field in the Properties window has two sections: the propertys name and the property's
value:
http://www.functionx.com/vbaexcel/Lesson07.htm
57
The name of a property is represented in the left column. This is the official name of the property.
Notice that the names of properties are in one word. Based on this, our House class would have
been defined as follows:
House
[
Address
TypeOfHouse
NumberOfBedrooms
NumberOfBathrooms
HasIndoorGarage
LivingRoomCoveredWithCarpet
KitchenHasIslandStove
]
You can use this same name to access the property in code.
http://www.functionx.com/vbaexcel/Lesson07.htm
Types of Properties
58
Empty Fields
Text Fields
There are fields that expect you to type
a value. Most of these fields have a
default value.
To change the value of the property,
click the name of the property, type the
desired value, and press Enter or Tab.
While some properties, such as the
Caption, would allow anything, some
other fields expect a specific type of
text, such as a numeric value.
To programmatically change the value
of a text-based property, on the right
side of the = sign, you can type the
value in double quotes. For example,
suppose you have a House object
named Langston. If you want to specify
its address, you would write:
Langston.Address = "6802 Leighton Ave"
Numeric Fields
Some fields expect a numeric value. In this case, you can click the name of the
field and type the desired value. If you type an invalid value, you would receive
a message box notifying you of the error:
When this happens, click OK and type a valid value. If the value is supposed to
be an integer, make sure you don't type it with a fractional part.
Expandable Fields
http://www.functionx.com/vbaexcel/Lesson07.htm
Boolean Fields
Some fields can have only a
True or False value. These are
Boolean fields. To change their
value, you can either select from
the combo box or double-click
the property to switch to the
other value.
To programmatically specify the
value of a Boolean property, on
the right side of the = symbol,
type True or False. Here is an
example:
Langston.HasIndoorGarage= True
Intermediary Fields
List-Based Fields
To change the value of some of the fields, you would first click the arrow of
their combo box to display the available values. After clicking the arrow, a list
would display:
http://www.functionx.com/vbaexcel/Lesson07.htm
59
60
There are various types of list-based fields. Some of them display just two
items. To change their value, you can just double-click the field. Some other
fields have more than two values in the list. To change them, you can click
their arrow and select from the list. You can also double-click a few times until
the desired value is selected. Some other items would dispplay a window from
where you would click the option you want:
tpeSingleFamily
tpeTownHouse
tpeCondominium
Although we used 0, 1, and 2 in this list, there are no predefined rules as to the
number allocated for each member of the list. The person who created the list
also decided what number, if any, each member of the list would have (if you
are curious, in most programming languages or libraries, these types of
properties are created using an enumeration (in C++ or in the the .NET
Framework) or a set (Borland VCL)). Based on this, the above code would also
be written as:
Langston.TypeOfHouse = 0
http://www.functionx.com/vbaexcel/Lesson07.htm
Previous
http://www.functionx.com/vbaexcel/Lesson07.htm
61
Next
62
Forms Fundamentals
Introduction to Forms
A computer application, such as those that run on Microsoft Windows, is equipped with objects
called Windows controls. These are the objects that allow a person to interact with the computer.
The primary control used on most applications is called a form.
Creating a Form
To create a form, on the main menu of Microsoft Visual Basic, you can click Insert -> UserForm.
This would add a form to your project. In the same way, you can add as many forms as you want.
The form is primarily used as a platform on which you add other controls. For this reason, a form
is referred to as a container. By itself, a form is not particularly useful. You should add other
objects to it.
When you create or add a form, a module is also automatically created for it. To access the
module associated with a form, you can right-click the form and click View Code.
Using a Form
Showing a Form
Although you create a form in Microsoft Visual Basic, you view its results in Microsoft Excel. You
have various options.
A form is referred to as modal if the user cannot access anything from the same application while
the form is displaying. A form is called modeless if the user can click something of the same
application behind that form while the form is displaying.
To display the run-time view of a form in modal view:
While in Microsoft Visual Basic, you can press F5
On the main menu of Microsoft Visual Basic, you can click Run -> Run Sub/UserForm
On the Standard toolbar of Microsoft Visual Basic, you can click the Run Sub/UserForm button
. This would send the form to Microsoft Excel and display it in the normal view
You can also programmatically display a form. To support this, the UserForm object is equipped
with a method named Show. Its syntax is:
Public Sub UserForm.Show(Optional ByVal Modal As Boolean)
This method takes one Boolean argument that is optional. If you omit it, the form would display as
modal and the user cannot do anything else in Microsoft Excel as long as the form is not closed.
That's the default behavior. If you want to display the form as modeless, pass the argument as
False. Here is an example:
Private Sub Exercise()
UserForm1.Show False
End Sub
Printing a Form
If you have equipped a form with many aesthetic objects you want to see on a piece of paper, you
http://www.functionx.com/vbaexcel/Lesson08.htm
can print it. To support printing, the UserForm object is equipped with a method named PrintForm.
Its syntax is:
Public Sub PrintForm
This method takes no argument. When called, it sends the (body of the) form directly to the
printer. Here is an example of calling it:
Private Sub Exercise()
UserForm1.PrintForm
End Sub
Hiding a Form
As opposed to displaying a form, if it is already showing, you can hide it. To allow you to hide a
form, the UserForm object is equipped with a method named Hide. Its syntax is:
Pyblic Sub UserForm.Hide
This method takes no argument. When called, it hides the form (without closing it). Here is an
example of calling it:
Private Sub Exercise()
UserForm1.Hide
End Sub
Closing a Form
After using a form, the user can close it by clicking the system close button. To programmatically
close a form, use the End statement. Here is an example:
Private Sub Exercise()
End
End Sub
http://www.functionx.com/vbaexcel/Lesson08.htm
63
64
Previous
Next
http://www.functionx.com/vbaexcel/Lesson08.htm
65
Controls Fundamentals
Introduction
By itself, a form means nothing. Its role is revealed in the objects it holds. You can add such
objects to a form or the body of a spreadsheet.
The Spreadsheet
When working in Microsoft Excel, you can use Windows controls either on the work area or in a
form in Microsoft Visual Basic. Therefore, just like a form, a spreadsheet also is a container of
controls.
This would display the list of controls available in Microsoft Excel. The controls appear in two
sections: Form Controls and ActiveX Controls. If you are working on a spreadsheet in Microsoft
Excel, you should use only the controls in the ActiveX Controls section. If you are working on a
form in Microsoft Visual Basic, a Toolbox equipped with various controls will appear.
http://www.functionx.com/vbaexcel/Lesson09.htm
66
http://www.functionx.com/vbaexcel/Lesson09.htm
67
You can scroll up and down in the window to locate the desired control. If you see a control you
want to use, click it and click OK.
In Microsoft Visual Basic, to access more controls, on the main menu, you can click Tools ->
Additional Controls... This would open the Additional Controls dialog box:
To select a control, you can click its check box. After selecting the controls, click OK.
Label
Combo Box
Toggle Button
Check Box
List Box
TabStrip
Text Box
MultiPage
Scroll Bar
ScrollBar
Spin Button
Text Box
Option Button
Image
Label
RefEdit
Image
Frame
Toggle Button
68
In our lessons, when working in Microsoft Excel, we will avoid using the objects in the Form
Controls section.
If you want, instead of clicking and releasing the mouse, you can click and drag. This allows you
to "draw" the control and give the dimensions of your choice. If the control has already been
added but you want it to assume different dimensions, you can click it to select it and then drag
one of its border handles.
To programmatically add a control to a spreadsheet, use the following formula:
Private Sub Exercise()
Worksheets(1).OLEObjects.Add "Forms.ControlName.1"
End Sub
The only thing you need to know and change about this formula is the ControlName factor. We
will learn about Worksheets(1) in Lesson 12. Use the following names:
Use this Name
To Get a
To Get
CheckBox
Check Box
ComboBox
Combo Box
CommandButton
Command Button
Label
Label
ListBox
List Box
Image
Image
OptionButton
Option Button
ScrollBar
Scroll Bar
SpinButton
Spin Button
TextBox
Text Box
ToggleButton
Toggle Button
http://www.functionx.com/vbaexcel/Lesson09.htm
Control Selection
Single Control Selection
After you have added a control to a container, in order to perform any type of
configuration on the control, you must first select it. Sometimes you will need to
select a group of controls.
To select a control in the work area in Microsoft Excel, first, in the Controls section
2. In the Controls section of the Ribbon, click the Design Mode button
http://www.functionx.com/vbaexcel/Lesson09.htm
69
If you are working on a form in Microsoft Visual Basic, first click one of the controls
you want to select, then press and hold Ctrl. Click each of the desired controls. If
you click a control that should not be selected, click it again. After selecting the
group of controls, release Ctrl that you were holding. As another technique you can
use to select various controls, click an unoccupied area on the form, hold the mouse
down, drawing a fake rectangle that would either include each of the desired
controls or would touch each, then release the mouse:
http://www.functionx.com/vbaexcel/Lesson09.htm
70
71
When a group of controls is selected, the first selected control displays 8 handles
but its handles are white while the others are dark.
Control Deletion
If there is a control on your form or your work area but you don't need it, you can
remove it. To delete a control, first select it and then press Delete. You can also
right-click a control and click Cut.
To remove a group of controls, first select them, then press Delete or right-click the
selection and click Cut.
Previous
Next
http://www.functionx.com/vbaexcel/Lesson09.htm
72
Basic button
3. To create a form, on the main menu of Visual Basic, click Insert -> UserForm
4. On the Toolbox, click the CommandButton and click somewhere on the form (no need for
precision)
5. On the Toolbox, click ComboBox and click the form away from the previously added
CommandButton
Moving a Control
When you add a control to the work area in Microsoft Excel or to a form in Microsoft Visual Basic,
it assumes a position on its container. If you want, you can change that location by moving the
control.
To move a control, click it and drag in the direction of your choice. To move a group of controls,
first select them. Click it and drag the selection in the direction of your choice
When a control has been selected, as your mouse moves over it, its pointer displays a different
cursor. One of these cursors can be used to move a control. This cursor is represented as a cross
with four arrows:
To move a control, click its border and hold the mouse down, drag in the direction of your choice.
When you get to the desired location, release the mouse.
Aligning Controls
Horizontal Alignment
When many controls are selected on a form, one of the controls has dark handles:
http://www.functionx.com/vbaexcel/Lesson10.htm
73
In our descriptions, the control with the dark handles will be referred to as the base control.
During form design, to better position the controls, you can use the main menu with the Format
group. Microsoft Visual Basic also provides the UserForm toolbar to assist you. To display the
UserForm toolbar, on the main menu of Microsoft Visual Basic, you can click View -> Toolbars ->
UserForm.
If you have a certain control on the form and want to position it exactly at equal distance between
the left and the right borders of the form, select the control, then, on the main menu of Microsoft
Visual Basic, click Format -> Center in Form -> Horizontally. To get the same option, on the
UserForm toolbar, click the arrow of the Center button and click Horizontally:
Horizontal alignment affects controls whose distance from the left border of the form must be the
same. To perform this type of alignment, you can use the main menu where you would click
Format -> Align, and select one of the following options:
Lefts: All selected controls will have their left border coincide with the left border of the base
control
Centers: The middle handles of the selected controls will coincide with the middle handles of
the base control
Rights: All selected controls will have their right border coincide with the right border of the
base control
To get the same options using the UserForm toolbar, click the arrow of the Align button and select
the desired option: Lefts, Centers, or Rights:
Vertical Alignment
Another option you have consists of moving controls up or down for better alignment. Once again
you must first select the controls. Then, on the main menu, click Format -> Align, and click one of
the following options:
Tops: All selected controls will have their top border coincide with the top border of the base
control but their left border would have the same distance with the left border of the parent
Middles: The top handles of the selected controls will align vertically with the top handle of
the base control
Bottoms: All selected controls will have their bottom border coincide with the bottom border
of the base control but their left border would have the same distance with the left border of
the parent
To get the same options using the UserForm toolbar, click the arrow of the Align button and select
the desired option: Tops, Middles, or Bottoms.
http://www.functionx.com/vbaexcel/Lesson10.htm
74
Obviously the controls on this form are not enjoying the most professional look. The Format group
of the main menu allows you to specify a better horizontal alignment of controls with regards to
each other. To use it, first select the controls. Then, on the main menu of Microsoft Visual Basic,
click Format -> Horizontal Spacing, and click one of the following options:
Make Equal: Microsoft Visual Basic will calculate the horizontal distances that separate each
combination of two controls and find their average. This average is applied to the horizontal
distance of each combination of two controls:
Increase: Microsoft Visual Basic will move each control horizontally, except the base control
(the control that has white handles) by one unit away from the base control. This will be done
every time you click the Increase Horizontal Spacing button or the Format -> Horizontal
Spacing -> Increase menu item
Decrease: Microsoft Visual Basic will move each control horizontally, except the base control
(the control that has white handles) by one unit towards the base control. This will be done
every time you click the Decrease Horizontal Spacing button or the Format -> Horizontal
Spacing -> Decrease menu item
Remove: Microsoft Visual Basic will move all controls (horizontally), except for the left
control, to the left so that the left border of a control touches the right border of the next
control
The controls on this form are not professionally positioned with regards to each other. Once again,
the Format group of the main menu allow you to specify a better vertical alignment of controls
relative to each other. To align them, on the main menu of Microsoft Visual Basic, click Format ->
Vertical Spacing and click one of the following options:
Make Equal: Microsoft Visual Basic will calculate the total vertical distances that separate
each combination of two controls and find their average. This average is applied to the vertical
distance of each combination of two controls
http://www.functionx.com/vbaexcel/Lesson10.htm
75
Increase: Microsoft Visual Basic will move each control vertically, except the base control
(the control that has darker handles) by one unit away from the base control. This will be
done every time you click the Increase Horizontal Spacing button or the Format -> Horizontal
Spacing -> Increase menu item
Decrease: Microsoft Visual Basic will move each control, except the base control (the control
that has darker handles) by one unit towards the base control. This will be done every time
you click the Decrease Horizontal Spacing button or the Format -> Horizontal Spacing ->
Decrease menu item
Remove: Microsoft Visual Basic will move all controls vertically, except for the top control, to
the top so that the top border of a control touches the bottom border of the next control
towards the top
http://www.functionx.com/vbaexcel/Lesson10.htm
Properties window, click Width and type the desired value. To programmatically specify the width
of a control, access it using its name, type the period, followed by Width, the assignment
operator, and the desired value.
If a control displays or contains text, such as the caption of a button, click the control. On the
main menu of Microsoft Visual Basic, click Format and click Size to Fit.
. Click and drag left or right until you get the desired
Imagine you would like each of these buttons to have just enough space to accommodate its
caption. First select the controls that will be resized. To resize the controls, on the main menu of
Microsoft Visual Basic, click Format and click Size to Fit. If you do, the controls will be resized
based on the contents of their value:
If all the controls are text boxes, their widths would be reduced to be able to hold a character.
Consider the following form:
Imagine one of the controls has a certain width and you want to apply that width to the other
controls. Select the controls but make as the base control the object that has the width you want.
Here is an example where the button labeled Order Processing is selected as the base:
http://www.functionx.com/vbaexcel/Lesson10.htm
76
On the main menu, you can click Format -> Make Same Size -> Width. Alternatively, on the
UserForm toolbar, you can click the arrow of the right button and click Width:
After doing this, the controls would be enlarged or narrowed based on the width of the control
that was set as the base:
To visual specify the height of a control, click it, position the mouse on one of its top or bottom
. Then click and
handle until the mouse cursor appears with a vertisal bar with two arrows
drag up or down in the direction of your choice until you get the desired height. Then release the
mouse.
To specify the width of a control with precision, click the control. In the Properties window, click
Height and type the desired value. To programmatically specify the height of a control, access it
using its name, type the period, followed by Height, followed by =, and the desired value.
http://www.functionx.com/vbaexcel/Lesson10.htm
77
If a control displays or contains text, such as the caption of a button, click the control. On the
main menu of Microsoft Visual Basic, click Format and click Size to Fit.
To programmatically specify the height of a control, type its name, access its Height property and
assign the desired value.
. Click
You can shrink or heighten many controls based on the height of one of the controls. To start,
select the controls but use as base the control that has the height you would like to apply on the
other controls. Here is an example where the button labeled Get is set as the base:
On the main menu, you can click Format -> Make Same Size -> Height. Or, on the UserForm
toolbar, you can click the arrow of the right button and click Height.
After doing this, the controls would get shrunk or tall based on the width of the control that was
set as the base:
http://www.functionx.com/vbaexcel/Lesson10.htm
78
79
To visually resize various controls, first select them. Position the mouse on the border or corner of
one of the selected controls until you get the cursor that would resize to the direction of your
choice:
Control Maintenance
Copying a Control
If you had applied some design on a control and you want to replicate that design, you can copy
the control. This is mostly a simple operation of copy n' paste. You can copy a control on the work
area or on a form and paste it on the same container (you are not allowed to copy a control from
the work area to a form and vice versa). You can also copy a control from one work area and
paste it in another work area. You can copy a control from one form and paste it in another form.
When you copy and paste a control, there are some characteristics it would retain and some
others it would loose. Normally, it would keep its aesthetic characteristics (such as the color) and
its size but it will loose some others (such as its location and its programmatic characteristics such
as its name.
To copy a control:
Right-click the control and click Copy
Click the control to select it and press Ctrl + C
To copy a group of controls, first select the controls:
Right-click in the selection and click Copy
Press Ctrl + C
To paste the copied controls, in the work area or on a form:
Right-click the destination (work area or form) and click Paste
Press Ctrl + V
Deleting Controls
If you have added a control to the work area or a form but you don't need it anymore, you can
remove it from the container. You can also delete a group of controls in one step.
To remove a control from a work area or from a form:
Click the control and press Delete
Right-click the control and click Cut
To remove a group of controls, select them:
Press Delete
http://www.functionx.com/vbaexcel/Lesson10.htm
Tab Ordering
When using the controls of a form, you can press Tab to move from one control to another. For
example, after entering a value in a text box of a form, if there is another text box on the right
side, when you press Tab, the caret should move to that right control. If there is no control on the
right side, the caret should move to the control under the one previously used. If the caret or
focus is in the last bottom control on a form and you press Tab, the caret should move back to the
first record. This follows the arranged sequence of the controls on the form. For this reason, the
controls on a form should be aligned in the order of a logical sequence.
When you add a control to a form that already has other controls, it is sequentially positioned at
the end of the existing controls. The sequence of controls navigation is set using the Tab Order
dialog box. To access the Tab Order dialog box:
Right-click the form and click Tab Order
On the main menu of Microsoft Visual Basic, click View -> Tab Order
Border Style
Some controls display a border when they are drawn and some others don't. Some of these
controls allow you to specify a type of border you want to show surrounding the control. This
characteristic is controlled by the BorderStyle property.
http://www.functionx.com/vbaexcel/Lesson10.htm
80
If a control displays text, it may have a property called Caption in the Properties window. After
adding such a control to a work area or a form, its Caption field would display the same text as
its name. At design time, to change the caption of the control, click its Caption field in the
Properties window and type the desired value. For most controls, there are no strict rules to follow
for this text. Therefore, it is your responsibility to type the right value. Some other controls have
this property named Text. For such a control, when you add it to a work area or a form, its Text
field in the Properties window may be empty. If you want, you can click the Text field and type
the desired text.
The text provided in Caption or a Text field of a text-based control can only be set as is
at design time. If you want the text to change while the application is running, you can format it.
For example, such a control can display the current time or the name of the user who is logged in.
These format attributes cannot be set at design time. To change the text of a text-based control at
run time, either assign a simple string or provide a formatted string to the Caption or the Text
property.
Result
1 - frmTextAlignLeft
2 - fmTextAlignCenter
3 - fmTextAlignRight
To programmatically specify the text alignment of a control that supports this characteristics,
assign the desired option to this property. Here is an example:
TextBox1.TextAlign = fmTextAlignRight
http://www.functionx.com/vbaexcel/Lesson10.htm
81
82
From this dialog box, you can select the font name, the style, the size, and the effect(s). Once you
are ready, click OK.
If you create a form in Microsoft Visual Basic, the origin of its location is located just under the
title bar to the left:
The horizontal measurements move from the origin to the right. The vertical measurements move
from the origin to the bottom. The location of a control is both:
The distance between the top border of the work area or of the form and the top border of the
control
The distance from the left border of the work area or of the form to the left border of the
control
http://www.functionx.com/vbaexcel/Lesson10.htm
83
In the Properties window, the distance between the top border of the work area or of the form and
the top border of the control is represented by the Top property. The distance between the left
border of the form and the left border of the control is represented by the Left property:
The Location of a Control on a Form
To move a control with precision, click it to select it and access its Properties window. In the
Properties window, change either or both the Left and the Top values. To programmatically specify
the location of a control, access its using its name. Then access its Width or its Height properties
and assign the desired value.
The width of a control is represented by the Width property. Therefore, to specify the width of a
control with precision, access it using its name, type the period, followed by Width, the
assignment operator, and the desired value.
To programmatically specify the height of a control, access it using its name, type the period,
followed by Height, followed by =, and the desired value.
http://www.functionx.com/vbaexcel/Lesson10.htm
84
To visual change a color, you can use the Properties window. In the Properties window, the fields
that support the color options are provided as a combo box. When you click the arrow of the
combo box, a window made of two parts would display:
The color window is divided in two property pages labeled Palette and System. The Palette
property page is probably the easiest section to specify a color because it provides small boxes
that each shows its color. The colors are represented each by a name. Those are official names
recognized by the Microsoft Windows operating systems but you should not use those colors in
your code.
To programmatically support colors, Microsoft Visual Basic provided two systems. Microsoft Visual
Basic provides a few constants values you can use as colors. These contants are:
Constants
Resulting Color
vbBlack
Black
vbBlue
Blue
vbCyan
Cyan
vbGreen
Green
vbMagenta
Magenta
vbRed
Red
vbWhite
White
vbYellow
Yellow
As you can see, this is a limited list. Obviously there should be other ways to specify a color. In
Microsoft Windows operating systems, a color is recognized as a number made of three parts. The
first part is small number that ranges from 0 to 255. This part represents the red section. The
second part also is a number from 0 to 255 and represents the green value.The third part also is a
number from 0 to 255 and represents the blue part. To support this, the Visual Basic language
provides a function named RGB and whose syntax is:
Function RGB(Red As Byte, Green As Byte, Blue As Byte) As Long
This function takes three arguments. Each argument should be a number between 0 and 255. If
the arguments are valid, the function would produce a Long value that represents a color
recognized by Microsoft Windows. Here is an example:
BackColor = RGB(28,174, 77)
As mentioned already, the RGB() function produces a Long integer that represents a color. If you
already know the number that represents the color, you can use it as the color. For example, you
can assign it to the colored property. Here is an example:
BackColor = 4912394
This number is provided in decimal format. As an alternative, you can provide it in hexadecimal
format. Here is an example:
BackColor = &HF420DD
http://www.functionx.com/vbaexcel/Lesson10.htm
85
To programmatically specify or change the text color of a control, access it. Then access its
ForeColor property and assign it the desired color.
Control's Visibility
A control is referred to as visible if it can be visually located on the screen. You can use a control
only if you can see it. You have the role of deciding whether a control must be seen or not and
when. The visibility of an object is controlled by the its Visible property.
At design time, when you add a control to the work area or to a form, it is visible by default. This
is because its Visible property is set to True in the Properties window. If you don't want a control
to primarily appear when the form comes up, you can set its Visible property to False.
Control's Availability
To be able to use a control, it must allow operations on it. For example, if a control is supposed to
receive text, you can enter characters in it only if this is made possible. To make a control
available, the object must be enabled. The availability of an object is controlled by the Enabled
property.
By default, after adding a control to a form, it is enabled and its Enabled property in the
Properties window is set to True. An enabled control displays its text or other characteristics in
their normal settings. If you want to disable a control, set its Enabled property to False.
http://www.functionx.com/vbaexcel/Lesson10.htm
86
Control
Caption/Text
Frame
Order Identification
Label
Employee #:
Name
TextBox
txtEmployeeNumber
TextBox
txtEmployeeName
Label
Customer Phone:
TextBox
txtCustomerPhone
TextBox
txtCustomerName
Label
Date Left:
TextBox
Label
txtDateLeft
Time Left:
TextBox
Label
txtTimeLeft
Date Expected:
TextBox
Label
txtDateExpected
Time Expected:
TextBox
Label
txtTimeExpected
Date Picked Up:
TextBox
Label
Other Properties
txtDatePickedUp
Time Picked Up:
TextBox
txtTimePickedUp
Frame
Items to Clean
Label
Item
Label
Unit Price
Label
Qty
Label
Sub-Total
Label
Shirts
TextBox
1.50
txtUnitPriceShirts
TextAlign: 3 fmTextAlignRight
TextBox
txtQuantityShirts
TextAlign: 3 fmTextAlignRight
http://www.functionx.com/vbaexcel/Lesson10.htm
txtSubTotalShirts
TextAlign: 3 fmTextAlignRight
2.25
txtUnitPricePants
TextAlign: 3 fmTextAlignRight
TextBox
txtQuantityPants
TextAlign: 3 fmTextAlignRight
TextBox
0.00
txtSubTotalPants
TextAlign: 3 fmTextAlignRight
ComboBox
None
cbxNameItem1
TextBox
0.00
txtUnitPriceItem1
TextAlign: 3 fmTextAlignRight
TextBox
txtQuantityItem1
TextAlign: 3 fmTextAlignRight
TextBox
0.00
txtSubTotalItem1
TextAlign: 3 fmTextAlignRight
ComboBox
None
cbxNameItem2
TextBox
0.00
txtUnitPriceItem2
TextAlign: 3 fmTextAlignRight
TextBox
txtQuantityItem2
TextAlign: 3 fmTextAlignRight
TextBox
0.00
txtSubTotalItem2
TextAlign: 3 fmTextAlignRight
ComboBox
None
cbxNameItem3
TextBox
0.00
txtUnitPriceItem3
TextAlign: 3 fmTextAlignRight
TextBox
txtQuantityItem3
TextAlign: 3 fmTextAlignRight
TextBox
0.00
txtSubTotalItem3
TextAlign: 3 fmTextAlignRight
ComboBox
None
cbxNameItem4
TextBox
0.00
txtUnitPriceItem4
TextAlign: 3 fmTextAlignRight
TextBox
txtQuantityItem4
TextAlign: 3 fmTextAlignRight
TextBox
0.00
txtSubTotalItem4
TextAlign: 3 fmTextAlignRight
Frame
Order Summary
Label
Cleaning Total:
TextBox
0.00
txtCleaningTotal
TextAlign: 3 fmTextAlignRight
Label
Tax Rate:
TextBox
5.75
txtTaxRate
TextAlign: 3 fmTextAlignRight
Label
Label
Tax Amount:
TextBox
0.00
txtTaxAmount
TextAlign: 3 fmTextAlignRight
Label
Order Total:
TextBox
0.00
txtOrderTotal
TextAlign: 3 fmTextAlignRight
Label
Order Status:
TextBox
0.00
Label
Pants
TextBox
cbxOrderStatus
ComboBox
Button
Close
btnClose
http://www.functionx.com/vbaexcel/Lesson10.htm
87
focus.
88
To give focus to a control, the user can click the intended control or press Tab a few times until
the control receives focus. To programmatically give focus to a control, type the name of the
control, followed by the period operator, followed by the SetFocus method. An example would be:
Private Sub Example()
txtAddress.SetFocus
End Sub
Previous
http://www.functionx.com/vbaexcel/Lesson10.htm
Next
89
Controls Messages
Introduction
You can add Windows controls to a work area or to a form to help a user interact your
application. When a control is used, it must communicate with the operating system. For
example, when a user clicks, the object that was clicked must inform the operating system that
it has been clicked. This is the case for every control used in an application. Because a typical
application can involve many controls, a mechanism was designed to manage the occurrence of
actions.
To communicate its intention to the operating system, a Windows control must compose a
message and send it (to the operating system).
By convention, the name of the message follows the name of the control but they are
separated with an underscore. It would appear as:
Private Sub ControlName_Push
Arguments: An argument is additional information needed to process a message. When a
control sends a message, it may need to accompany it with some information. For example, if
you position the mouse on a control and click, the operating system may need to know what
button of the mouse was used to click. On the other hand, if you select an object and start
dragging, the operating system may need to know if a key such as Shift or Ctrl was held down
while you were dragging.
http://www.functionx.com/vbaexcel/Lesson11.htm
An additional piece of information that the control provides is provided as an argument. While
some messages may need to provide only one piece of information, some messages would
require more than one argument. Some other messages don't need any additional information
at all: the name of the message would completely indicate how the message must be
processed.
The arguments of a message are provided in parentheses. They would appear as:
Private Sub ControlName_Push(Argument1, Argument2, Argument_n)
After specifying the message, you can type code that tells the operating system what to do to
process the message. To indicate the end of the code that relates to a message, type End Sub
Private Sub ControlName_Push(Argument1, Argument2, Argument_n)
End Sub
As mentioned earlier, a message must be composed and sent. The action of sending a message is
called an event. It is also said that the controls "fires" an event. Based on the above descriptions,
to compose and send a message, in the Object combo box, you can select the name of the control
that will send the message, then select the desired message in the Procedure combo box. When
you do this, Microsoft Visual Basic will write the first line that specifies the name of the control,
the name of the event, its arguments if any, and would write End Sub for you. You can then enter
the necessary code between those two lines.
Most Windows control have a special event referred to as the default. This is the even that is the
most obvious that the control can fire. For example, when you think of a button, the first action
that comes to mind is Click. For this reason, Click is the default event of a button. If you add a
control to a work area or to a form and double-click the control, its default event would be
invoked and the skeleton of that event would be written in the corresponding module. If you don't
want to use that event or to fires another event for the same control, you can simply select the
event in the Procedure combo box.
Control
Name
Caption
Label
lblHourlySalary
Hourly Salary:
TextBox
txtHourlySalary
Label
lblWeeklyHours
TextBox
txtWeeklyHours
CommandButton
cmdCalculate
Label
lblWeeklySalary
TextBox
txtWeeklySalary
Other Properties
TextAlign: 3 - frmTextAlignRight
Weekly Hours:
TextAlign: 3 - frmTextAlignRight
Weekly Salary:
TextAlign: 3 - frmTextAlignRight
http://www.functionx.com/vbaexcel/Lesson11.htm
90
on a Windows control. Based on this, the control that is clicked "owns" the event and must
manage it. Therefore, no detailed information is provided as part of the event. The operating
system believes that the control that fired the event knows what to do. For this reason, whenever
you decide to code an OnClick event, you should make sure you know what control sent or fired
the event. This is (one of) the most common events of Windows controls.
Sub cmdCalculate_Click()
HourlySalary As Currency
WeeklyHours As Double
WeeklySalary As Currency
HourlySalary = CCur(txtHourlySalary.Text)
WeeklyHours = CDbl(txtWeeklyHours.Text)
WeeklySalary = HourlySalary * WeeklyHours
txtWeeklySalary.Text = CStr(WeeklySalary)
End Sub
3. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
4. Enter 15.48 in the Hourly Salary and 36.50 in the Weekly Hours text boxes and click
Calculate
Double-Click
Another common action you perform on a control may consist of double-clicking it. This action
causes the control to fire an event known as DblClick.
http://www.functionx.com/vbaexcel/Lesson11.htm
91
Entering a Control
92
Just as an application can have many forms, a form can be equipped with various controls. Such is
the case for any data entry form. On a form that is equipped with many controls, only one control
can be changed at a time. Such a control is said to have focus. To give focus to a control, you can
click it or can keep pressing Tab until the desired control indicates that it has focus. In a form with
many controls, the control that has focus may display a caret or a dotted line around its selection
or its caption.
When a form or a control receives focus, it fires the Enter event. We mentioned that a user can
give focus to a control by clicking it. If the control is text-based, then a caret blinking in the
control indicates that the control has focus.
The Enter event does not take any argument:
Private Sub TextBox1_Enter()
End Sub
Exiting a Control
After using a control, you can switch to another control either by clicking another or by pressing
Tab. This causes the focus to shift from the current control to another. If the focus shifts to
another control, the control that had focus fires an Exit event.
The Exit event takes one argument, :
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
End Sub
Keyboard Events
Word processing consists of manipulating text and characters on your computer until you get the
fantastic result you long for. To display these characters, you press some keys on your keyboard.
If the application is configured to receive text, your pressing actions will display characters on the
screen. The keyboard is also used to perform various other actions such as accepting what a
dialog box displays or dismissing it.
When you press the keys on a keyboard, the control in which the characters are being typed
sends one or more messages to the operating system. There are three main events that Microsoft
Windows associates to the keyboard.
KeyDown: When you press a key on the keyboard, an event called KeyDown is fired. The
KeyDown event takes two arguments:
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
End Sub
KeyUp: When you release a key that was pressed, an event called KeyUp fires.
These two previous events apply to almost any key on the keyboard, even if you are not typing;
that is, even if the result of pressing a key did not display a character on the document.
Private Sub TextBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
End Sub
KeyPress: The KeyPress event fires if the key you pressed is recognized as a character key;
that is, a key that would result in displaying a character in a document.
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
End Sub
Some keys on the keyboard don't display anything on a document. Instead, they perform (only)
an action. Examples of such keys are Enter, Tab, Esc. Therefore, if you mean to find out what key
you pressed, use the KeyDown event instead of the KeyPress event.
http://www.functionx.com/vbaexcel/Lesson11.htm
93
Changing Text
One of the most important messages of a text box occurs when its content changes.
That is, when the text it has is deleted, added to, or edited. When you click in a text
box control and start typing it or change its text, the control fires a Change event.
Control
Name
Label
TextBox
Caption
First
Name:
txtFirstName
http://www.functionx.com/vbaexcel/Lesson11.htm
94
Last
Name:
Label
TextBox
txtLastName
Full
Name:
Label
TextBox
txtFullName
4. Double-click the top text box and implement its Change event as follows:
Private
Dim
Dim
Dim
Sub txtFirstName_Change()
FirstName As String
LastName As String
FullName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
FullName = FirstName & " " & LastName
txtFullName.Text = FullName
End Sub
5. In the Object combo box, select txtLastName and implement its Change event as
follows:
Private
Dim
Dim
Dim
Sub txtLastName_Change()
FirstName As String
LastName As String
FullName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
FullName = FirstName & " " & LastName
txtFullName.Text = FullName
End Sub
6. To test the form, on the main menu of Visual Basic, click Run -> Run
Sub/UserForm
7. Click the top text box, type Julienne and press Tab
8. In the other text box, start typing Pal and notice that the Full Name text box is
changing
Previous
Next
http://www.functionx.com/vbaexcel/Lesson11.htm
95
Fundamentals of Collections
Introduction
A collection is a series of items where each item has the same characteristics. In other words, all
items can be described the same way. Programmatically, a collection is a series of items where
all items share the same properties and methods, if any. For example, a collection can be made
of employees of a company where each employee can be described with a characteristics such as
a name.
Creating a Collection
In our lessons, we will not create new collections. We will only use two categories: the Collection
class and the built-in collection.
To support collections, the Visual Basic language is equipped with a class named Collection.
Actually, the Collection class we are going to study here is the one defined in VBA. The parent Visual
Basic language has a somewhat different Collection class with additional functionality not found in the
VBA's version.
This class can be used to create a collection. To do this, declare a variable of type Collection. Here
is an example:
http://www.functionx.com/vbaexcel/Lesson12.htm
Sub Exercise()
Dim Employees As Collection
End Sub
96
After declaring the variable, to allocate memory for it, use the Set operator to assign a New
instance to the variable. Here is an example:
Sub Exercise()
Dim Employees
As Collection
As Collection
As Collection
"Patricia Katts"
"James Wiley"
"Gertrude Monay"
"Helene Mukoko"
Remember that if you are using one of the built-in collection classes, you do not have to declare a
variable for it. You can just call the Add method on it to add an item to it. Here is an example:
Sub Exercise()
Worksheets.Add
End Sub
http://www.functionx.com/vbaexcel/Lesson12.htm
"None"
"Women Suit"
"Dress"
"Regular Skirt"
"Skirt With Hook"
"Men 's Suit 2Pc"
"Men 's Suit 3Pc"
"Sweaters"
"Silk Shirt"
"Tie"
"Coat"
"Jacket"
"Swede"
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
cbxNameItem3.AddItem
"None"
"Women Suit"
"Dress"
"Regular Skirt"
"Skirt With Hook"
"Men 's Suit 2Pc"
"Men 's Suit 3Pc"
"Sweaters"
"Silk Shirt"
"Tie"
"Coat"
"Jacket"
"Swede"
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
cbxNameItem4.AddItem
"None"
"Women Suit"
"Dress"
"Regular Skirt"
"Skirt With Hook"
"Men 's Suit 2Pc"
"Men 's Suit 3Pc"
"Sweaters"
"Silk Shirt"
"Tie"
"Coat"
"Jacket"
"Swede"
As Collection
http://www.functionx.com/vbaexcel/Lesson12.htm
97
98
"Patricia Katts"
"James Wiley"
"Gertrude Monay"
"Helene Mukoko"
Employees.Item 2
End Sub
Remember that you an also use parentheses:
Sub Exercise()
Dim Employees
As Collection
"Patricia Katts"
"James Wiley"
"Gertrude Monay"
"Helene Mukoko"
Employees.Item (2)
End Sub
Instead of using the Item property, you can apply the index directly to the collection
object. Here are examples:
Sub Exercise()
Dim Employees
As Collection
"Patricia Katts"
"James Wiley"
"Gertrude Monay"
"Helene Mukoko"
Employees.Item 2
Employees.Item (2)
Employees 2
Employees (2)
End Sub
All these four techniques (notations) give you access to the item whose index you
provided.
As Collection
"Patricia Katts"
"James Wiley"
"Gertrude Monay"
"Helene Mukoko"
Employees.Remove 2
End Sub
This code deletes the second item in the collection.
http://www.functionx.com/vbaexcel/Lesson12.htm
We also know how to remove an item from a collection. Whenever an existing item
is deleted, the value of the Count property is decreased by 1.
99
At anytime, to know the number of items that a collection is currently holding, get
the value of its Count property.
Previous
http://www.functionx.com/vbaexcel/Lesson12.htm
Next
100
Workbooks Fundamentals
Introduction
When you start Microsoft Excel, it immediately creates a new workbook. You can start working
on it and, eventually, you can save it. You are then said to save the workbook. On the other
hand, if you have an existing workbook somewhere in the computer or from an attached
document sent from a message to you, you can open it as a document.
Option Explicit
Private AutoRepairExists As Boolean
Private Sub cmdNewAutoRepair_Click()
AutoRepairExists = False
End Sub
15. Return to Microsoft Excel
Referring to a Workbook
In the VBA language, a workbook is an object that belongs to a collection called Workbooks.
Each workbook of the Workbooks collection is an object of type Workbook, which is a class.
As seen in the previous lesson with regards to collections, each workbook of the Workbooks
collection can be identified using the Item property. To programmatically refer to a workbook,
access the Item property and pass either the index or the file name of the workbook to it.
After referring to a workbook, if you want to perform an action on it, you must get a reference to
it. To do this, declare a Workbook variable and assign the calling Item() to it. This would be
done as follows:
Private Sub cmdSelectWorkbook_Click()
Dim SchoolRecords As Workbook
http://www.functionx.com/vbaexcel/Lesson13.htm
101
Creating a Workbook
When it starts, Microsoft Excel creates a default blank workbook for you. Instead of using an
existing workbook or while you are working on another workbook, at any time, you can create a
new workbook.
As mentioned already, a workbook is an object of type Workbook and it is part of the
Workbooks collection. To support the ability to create a new workbook, the Workbooks
collection is equipped with a method named Add. Its syntax is:
Workbooks.Add(Template) As Workbook
You start with the Workbooks class, a period, and the Add method. This method takes only one
argument but the argument is optional. This means that you can call the method without an
argument and without parentheses. Here is an example:
Private Sub cmdNewWorkbook_Click()
Workbooks.Add
End Sub
When the method is called like this, a new workbook would be created and presented to you. After
creating a workbook, you may want to change some of its characteristics. To prepare for this,
notice that the Add() method returns a Workbook object. Therefore, when creating a workbook,
get a reference to it. To do this, assign the called method to a Workbook variable. Here is an
example:
Private Sub cmdNewWorkbook_Click()
Dim SchoolRecords As Workbook
Set SchoolRecords = Workbooks.Add
End Sub
After doing this, you can then use the new variable to change the properties of the workbook.
To support the ability to programmatically change the default folder, the Application class is
equipped with a property named DefaultFilePath. Therefore, to programmatically specify the
default folder, assign its string to the Application.DefaultFilePath property. Here is an example:
Private Sub Exercise()
Application.DefaultFilePath = "C:\Georgetown Dry Cleaning Services"
End Sub
http://www.functionx.com/vbaexcel/Lesson13.htm
When this code has executed, the Default File Location of the Excel Options dialog box would be
changed.
Saving a Workbook
To visually save a workbook, you can click the Office Button and click Save. You can also press
Ctrl + S. If the document was saved already, it would be saved behind the scenes without your
doing anything else.
To support the ability to programmatically save a workbook, the Workbook class is equipped with
a method named Save. Its syntax is:
Workbook.Save()
As you can see, this method takes no argument. If you click the Office Button and click Save or if
you call the Workbook.Save() method on a work that was not saved yet, you would be prompted
to provide a name to the workbook.
To save a workbook to a different location, you can click the Office Button, position the mouse on
Save As and select from the presented options. You can also press F12. To assist you with
programmatically saving a workbook, the Workbook class is equipped with a method named
SaveAs. Its syntax is:
Workbook.SaveAs(FileName,
FileFormat,
Password,
WriteResPassword,
ReadOnlyRecommended,
CreateBackup,
AccessMode,
ConflictResolution,
AddToMru,
TextCodepage,
TextVisualLayout,
Local)
The first argument is the only required one. It holds the name or path to the file. Therefore, you
can provide only a name of the file with extension when you call it. Here is an example:
Private Sub cmdNewWorkbook_Click()
Dim SchoolRecords As Workbook
Set SchoolRecords = Workbooks.Add
SchoolRecords.SaveAs "SchoolRecords.xlsx"
End Sub
If you provide only the name of a file when calling this method, the new workbook would be saved
in the current directory or in My Documents (Documents in Windows Vista). If you want, an
alternative is to provide a complete path to the file.
web,
pass the
first
and the
second argument
of
the
http://www.functionx.com/vbaexcel/Lesson13.htm
102
103
Workbook.SaveAs(FileName, FileFormat)
In this case, pass the second argument as xlHTML. Here is an example:
Sub Exercise()
Workbooks(1).SaveAs "Affiche10.htm", xlHtml
End Sub
Opening a Workbook
Microsoft Excel is a multiple document interface (MDI) application. This means that you can open
many workbooks at the same time and be limited only by the memory on your computer. For this
reason, the ability to programmatically open a workbook is handled by the Workbooks collection.
To support this, the Workbooks class is equipped with a method named Open. Its syntax is:
Workbooks.Open(FileName,
UpdateLinks,
ReadOnly,
Format,
Password,
WriteResPassword,
IgnoreReadOnlyRecommended,
Origin,
Delimiter,
Editable,
Notify,
Converter,
AddToMru,
Local,
CorruptLoad)
FileName is the only required argument. When calling this method, you must provide the name of
the file or its path. This means that you can provide a file name with its extension. Here is an
example:
Private Sub cmdOpenWorkbook_Click()
Workbooks.Open "SchoolRecords.xlsx"
End Sub
If you provide only the name of a file, Microsoft Excel would look for it in the current directory or in
My Documents (Documents in Windows Vista). If Microsoft Excel cannot file the file, you would
receive an error:
As you can imagine, a better alternative is to provide a complete path to the file.
http://www.functionx.com/vbaexcel/Lesson13.htm
104
Closing Workbooks
Closing a Workbook
After using a workbook or to dismiss a document you don't need, you can close it. To support this
operation, the Workbook class is equipped with a method named Close. Its syntax is:
Public Sub Close(Optional ByVal SaveChanges As Boolean,
Optional ByVal Filename As String,
Optional ByVal RouteWorkbook As Boolean)
All three arguments are optional. The first argument indicates whether you want to save the
changes, if any have been made on the workbook since it was opened. If no change had been made
since the time the workbook was created or since the last time it was opened, this argument is not
considered.
If the first argument is set to True and the workbook has changes that need to be save, the second
argument specifies the name of the file to save the workbook to.
The third argument specifies whether the workbook should be sent to the next user.
http://www.functionx.com/vbaexcel/Lesson13.htm
105
If you have many workbooks you don't need, you can close all of them. To support this operation,
the Workbooks collection class is equipped with a method named Close. Its syntax is:
Public Sub Workbooks.Close()
This method takes no argument. When called, it closes all workbooks that are currently opened in
Microsoft Excel.
Sub Exercise()
Windows.Arrange ArrangeStyle:=xlTiled
End Sub
Horizontal:
Sub Exercise()
Windows.Arrange ArrangeStyle:=xlHorizontal
End Sub
Vertically:
Sub Exercise()
Windows.Arrange ArrangeStyle:=xlVertical
End Sub
Cascade:
Sub Exercise()
Windows.Arrange ArrangeStyle:=xlCascade
End Sub
Accessing a Workbook
To access a workbook, the Workbook class is equipped with a method named Activate. Its syntax
is:
Workbook.Activate()
This method takes no argument. Therefore, to call it, you can get a reference to the workbook you
want to access, then call the Activate() method. Here is an example:
Private Sub cmdSelectWorkbook_Click()
Dim SchoolRecords As Workbook
Set SchoolRecords = Workbooks.Item(2)
SchoolRecords.Activate
End Sub
You can also do this with less code by applying the index directly to the Workbooks collection. Here
is an example:
Private Sub cmdSelectWorkbook_Click()
Workbooks(2).Activate
End Sub
Previous
http://www.functionx.com/vbaexcel/Lesson13.htm
Next
106
http://www.functionx.com/vbaexcel/Lesson13.htm
107
Worksheets Fundamentals
Introduction
A worksheet is a document in Microsoft Excel. A worksheet is an object created inside a
workbook. That is, a workbook is a series of worksheets that are treated as a group.
Identifying a Worksheet
A worksheet is an object of type Worksheet. The various worksheets you will use are stored in a
collection called Worksheets. Another name for the collection that contains the worksheets is
called Sheets. In most cases, you can use either of these two collections. Each worksheet is an
object of type Worksheet.
Referring to a Worksheet
In the previous lesson, we saw that, if you have only one workbook opened, to refer to it, you
can pass an index of 1 to the Item property of the Workbooks collection to access its Workbook
object. Here is an example:
Sub Exercise()
Workbooks.Item(1)
End Sub
You can omit the Item name if you want and you would get the same result:
Sub Exercise()
Workbooks(1)
End Sub
Because the worksheets of a document are part of the workbook that is opened, to support them,
the Workbook class is equipped with a property named Worksheets or Sheets. Therefore, after
identifying the workbook, use the period operator to access the Worksheets or the Sheets
property. Here is an example:
Sub Exercise()
Workbooks.Item(1).Sheets
End Sub
As mentioned already, the worksheets are stored in the Worksheets collection, which is actually
a class. Each worksheet can be located based on an indexed property named Item. The Item
property is a natural number that starts at 1. The most left worksheet has an index of 1. The
second worksheet from left has an index of 2, and so on. To access a worksheet, type one of the
Worksheets or Sheets collections, followed by the period operator, followed by Item() and,
between the parentheses, type the index of the worksheet you want. For example, the following
code will access the second worksheet from left:
Private Sub Exercise()
Workbooks.Item(1).Sheets.Item(2)
End Sub
Just as we saw that you can omit the Item word on the Workbooks object, you can also omit it
on the Worksheets or the Sheets object. This can be done as follows:
Sub Exercise()
Workbooks.Item(1).Worksheets(2)
End Sub
http://www.functionx.com/vbaexcel/Lesson14.htm
Or as follows:
108
Sub Exercise()
Workbooks(1).Worksheets(2)
End Sub
Each tab of a worksheet has a label known as its name. By default, the most left tab is labeled
Sheet1. The second tab from left is labeled Sheet2. To refer to a worksheet using its label, call the
Worksheets or the Sheets collection and pass the label of the tab you want, as a string. Here is
an example that refers to the worksheet labeled Sheet3:
Sub Exercise()
Workbooks.Item(1).Sheets.Item("Sheet3")
End Sub
On all the code we have written so far, we were getting a worksheet from the currently opened
workbook. As mentioned already, by default, when Microsoft Excel starts, it creates a default
workbook and gets a Workbooks.Item(1) reference. This means that you do not have to
indicate that you are referring to the current workbook: it is already available. Consequently, in
your code, you can omit Workbooks.Item(1) or Workbooks(1). Here is an example:
Sub Exercise()
Sheets.Item("Sheet3")
End Sub
Selecting a Worksheet
To select a worksheet, access the Sheets collection, pass the name of the desired worksheet as
string, and call Select. Here is an example that selects a worksheet labeled Sheet1:
Private Sub Exercise()
Sheets("Sheet1").Select
End Sub
The worksheet that is selected and that you are currently working on is called the active
worksheet. It is identified as the ActiveSheet object (it is actually a property of the current
document).
Worksheets Names
To rename a worksheet, pass its index or its default name as a string to the Sheets (or the
Worksheets) collection, then access the Name property of the collection and assign the desired
name. Here is an example:
Private Sub Exercise()
Sheets("Sheet1").Name = "Employees Records"
End Sub
This code will change the name of the Sheet1 worksheet to Employees Records.
As we saw earlier, you can refer to, or select, a worksheet, using its name. If you had renamed a
worksheet, you can use that name to select it. Here is an example that selects a worksheet named
Tuition Reimbursement:
Private Sub Exercise()
Sheets("Tuition Reimbursement").Select
End Sub
Control
Name
Caption
Label
TextBox
Label
Rename:
txtSheetOldName
As
http://www.functionx.com/vbaexcel/Lesson14.htm
TextBox
txtNewName
CommandButton
cmdRename
109
Rename
6. Click Rename and notice that the To rename the first worksheet, double-click the Sheet1 tab
to put it in edit mode
7. In the Rename text box, type Sheet2
8. In the As text box, type Emergency Information and click Rename
http://www.functionx.com/vbaexcel/Lesson14.htm
110
In this case, the name of the worksheet you are passing as argument must exist. Otherwise you
would receive an error. Instead of using the name of the worksheet, you can pass the numeric
index of the worksheet that you want to copy. For example, the following code will create a new
workbook that contains one worksheet named Sheet3:
Private Sub CommandButton1_Click()
Sheets.Item(3).Move
End Sub
If calling the Item property, make sure the index is valid, otherwise you would receive an error.
To actually move a worksheet, you must specify whether it would be positioned to the left or the
right of an existing worksheet. To position a worksheet to the left of a worksheet, assign it the
Before factor. To position a worksheet to the left of a worksheet, assign it the After argument.
Consider the following code:
Private Sub cmdMove_Click()
Worksheets("Sheet3").Move After:=Worksheets("Sheet1")
End Sub
This code will move the worksheet named Sheet3 to the right of a worksheet named Sheet1.
Control
Name
Caption
Create a
new
worksheet
named:
Label
TextBox
txtNewWorksheet
CommandButton
cmdNewWorksheet
2. Double-click the Create button and implement its Click event as follows:
http://www.functionx.com/vbaexcel/Lesson14.htm
111
5. Click Create
6. In the same way, create new worksheets named 5th Grade, 4th Grade, 3rd Grade, 2nd
Grade, and 1st Grade
7. Close the form
Removing Worksheets
To remove a worksheet, call the Delete() method of its collection. When calling this method, pass
the name of the worksheet you want to remove to the collection.
Control
Name
Label
TextBox
Caption
Delete the worksheet named:
txtRemoveSheet
CommandButton cmdDelete
Delete
2. Double-click the Create button and implement its Click event as follows:
http://www.functionx.com/vbaexcel/Lesson14.htm
3. To test the code, on the Standard toolbar of Microsoft Visual Basic, click the Run
Sub/UserForm button
4. Click the Delete The Worksheet Named text box, type Sheet3
5. Click Delete
Accessing a Worksheet
To access a worksheet, the Worksheet class is equipped with a method named Activate. Its
syntax is:
Worksheet.Activate()
This method takes no argument. To call it, get a reference to the worksheet you want to access
and call the Activate() method. You can also do this with less code by applying the index directly
to the Worksheets collection. Here is an example:
Private Sub cmdSelectWorkbook_Click()
Worksheets(2).Activate
End Sub
http://www.functionx.com/vbaexcel/Lesson14.htm
112
http://www.functionx.com/vbaexcel/Lesson14.htm
113
114
Worksheets(5).Activate
End Sub
41. On the Standard toolbar, click the Run Sub/UserForm button
42. Click each button and notice that the corresponding worksheet displays
43. Close the form
44. Close Microsoft Visual Basic
45. Close Microsoft Excel
46. If asked whether you want to save, click No
Previous
http://www.functionx.com/vbaexcel/Lesson14.htm
Next
115
Columns Fundamentals
Introduction
A worksheet is arranged in columns. In VBA for Microsoft Excel, to programmatically refer to a
column, you will use a collection. In your code, one of the classes you can use to access a
column is named Range. As we will see in various examples, you can directly access this class.
If you want to get a reference to a column or a group of columns, declare a variable of type
Range:
Sub Exercise()
Dim Series As Range
End Sub
To initialize the variable, you will identify the workbooks and the worksheets you are using. We
will see various examples later on.
Identifying a Column
A Column by its Index
The columns on a worksheet are arranged by positions. A position is in fact referred to as the
index of the column. The first column on the left has the index 1, the second from left has the
index 2, and so on. Based on this, to refer to its column, pass its index to the parentheses of the
Columns collection. Here are two examples:
Sub Exercise()
REM This refers to the first column
Workbooks(1).Worksheets(2).Columns(1)
' This refers to the 12th column
Workbooks(1).Worksheets(2).Columns(12)
End Sub
In the previous lesson, we saw that you can omit calling the Workbooks(1) property to identify
the first workbook if you know you are referring to the default workbook. Therefore, the above
codee can be written as follows:
Sub Exercise()
REM This refers to the fourth column
Worksheets(2).Columns(4)
End Sub
This code now indicates that you are referring to the fourth column in the second worksheet.
When this code runs, Microsoft Excel must be displaying the second worksheet. If you run this
code while Microsoft Excel is displaying a worksheet other than the second, you would receive an
error:
http://www.functionx.com/vbaexcel/Lesson15.htm
This means that if you trying accessing a column from a worksheet other than the one indicated in
your code, the code would fail. If you want to access a specific column in any worksheet from the
workbook that Microsoft Excel is currently showing, you can omit indicating the worksheet from
the Worksheets collection. Here is an example:
Sub Exercise()
REM This refers to the fourth column
Columns(4)
End Sub
This time, the code indicates that you are referring to the fourth column of whatever worksheet is
currently active.
Adjacent Columns
To programmatically refer to adjacent columns, you can use the Columns collection. In its
parentheses, type the name of a column that would be on one end of the range, followed by a
colon ":", followed by the name of the column that would on the other end. Here is an example
that refers to columns in the range D to G:
Sub ColumnReference()
Rem Refer to the range of columns D to G
Columns("D:G")
End Sub
You can also select columns using the Range class. To do this, in the ch the name of the first
column, followed by a colon, followed by the name of the column on the other end. Here is an
example:
Sub ColumnReference()
Rem This refers to the columns in the range D to G
Range("D:H")
End Sub
Non-Adjacent Columns
Columns are refered to as non-adjacent when they do not follow each other. For example,
columns B, D, and G are non-adjacent. To programmatically refer to non-adjacent columns, use
the Range collection. In its parentheses, type each name of a column, followed by a colon,
followed by the same name of column, then separate these combinations with commas. Here is an
example:
Sub Exercise()
Rem This refers to Column H, D, and B
Range("H:H, D:D, B:B")
End Sub
To refer to all columns of a worksheet, use the Columns name. Here is an example:
Sub Exercise()
Columns
End Sub
Columns Selection
Selecting a Column
To support column selection, the Column class is equipped with a method named Select. This
method does not take any argument. Based on this, to select the fourth column using its indexed,
you would use code as follows:
Sub Exercise()
Rem This selects the fourth column
Columns(4).Select
End Sub
To select a column using its name, you would use code as follows:
Sub Exercise()
Rem This selects the column labeled ADH
http://www.functionx.com/vbaexcel/Lesson15.htm
116
Columns("ADH").Select
End Sub
117
When a column has been selected, it is stored in an object called Selection. You can then use
that object to take an action to apply to the column.
Creating Columns
Adding a New Column
To support the creation of columns, the Column class is equipped with a method named Insert.
This method takes no argument. When calling it, you must specify the column that will succeed
the new one. Here is an example that will create a new column in the third position and move the
columns from 3 to 16384 to the right:
Sub CreateColumn()
Columns(3).Insert
End Sub
Deleting Columns
Deleting a Column
To provide the ability to delete a column, the Column class is equipped with a method named
Delete. This method does not take an argument. To delete a column, use the Columns collection
to specify the index or the name of the column that will be deleted. Then call the Delete method.
Here is an example that removes the fourth column. Here is an example:
Sub DeleteColumn()
Columns("D:D").Delete
End Sub
http://www.functionx.com/vbaexcel/Lesson15.htm
Sub DeleteColumns()
Columns("D:F").Delete
End Sub
118
To delete many non-adjacent columns, use the Range class then call the Delete method of the
Column class. Here is an example that deletes Columns C, E, and P:
Sub DeleteColumns()
Range("C:C, E:E, P:P").Delete
End Sub
http://www.functionx.com/vbaexcel/Lesson15.htm
119
Previous
http://www.functionx.com/vbaexcel/Lesson15.htm
Next
120
Rows Fundamentals
Introduction
We already know that a worksheet organizes its information in columns. To show the values in a
worksheet, each column holds a particular value that corresponds to another value in the same
horizontal range. The group of values that correspond to the same horizontal arrangement is
called a row.
Identifying a Row
To support the rows of a worksheet, the Worksheet class is equipped with a property named
Rows. Therefore, to refer to a row, you can use the Worksheets collection or the Worksheet
object to access the Rows property. Another way you can refer to rows is by using the Range
object.
To identify a row, indicate its worksheet and you can pass its number to the parentheses of the
Rows collection. Here is an example that refers to the 5th row of the second worksheet of the
current workbook:
Sub Exercise()
Workbooks.Item(1).Worksheets.Item(2).Rows(5)
End Sub
As reviewed for the columns, this code would work only if the second worksheet of the current
workbook is displaying. If you run it while a worksheet other than the second is active, you would
receive an error. To access any row, omit the Workbooks and the Worksheets collections.
As mentioned already, you can refer to a row using the Range object. To do that, pass a string to
the Range object. In the parentheses, type the number of the row, followed by a colon, followed
by the number of the row. Here is an example that refers to Row 4:
Sub Exercise()
Range("4:4")
End Sub
If you want to refer to the rows more than once, you can declare a variable of type Range and
initialize it using the Set operator and assign it the range you want. Here is an example:
Sub Exercise()
Dim SeriesOfRows As Range
Set SeriesOfRows = Workbooks.Item(1).Worksheets.Item("Sheet1").Range("4:4")
SeriesOfRows.Whatever
End Sub
http://www.functionx.com/vbaexcel/Lesson16.htm
Sub Exercise()
Rows
End Sub
121
Rows Selection
Selecting a Row
To support row selection, the Row class is equipped with a method named Select. Therefore, to
programmatically select a row, access a row from the Rows collection using the references we
saw earlier. Then call the Select method. Here is an example that selects Row 6:
Sub Exercise()
Rows(6).Select
End Sub
We also saw that you could refer to a row using the Range object. After accessing the row, call the
Select method. Here is an example that selects Row 4:
Sub Exercise()
Range("4:4").Select
End Sub
When a row has been selected, it is stored in an object called Selection. You can then use that
object to apply an action to the row.
Managing Rows
The Height of a Row
To support the height of a row, the Row object is equipped with a property named RowHeight.
Therefore, to programmatically specify the height of a row, access the row using a reference as we
saw earlier, access its RowHeight property and assign the desired value to it. Here is an example
that sets the height of Row 6 to 2.50
Sub Exercise()
Rows(6).RowHeight = 2.5
End Sub
http://www.functionx.com/vbaexcel/Lesson16.htm
Sub Exercise()
Range("3:3, 6:6, 10:10").Insert
End Sub
122
Removing Rows
Deleting a Row
To support row removal, the Row class is equipped with a method named Delete
that takes no argument. Based on this, to delete a row, access it using a reference
as we saw earlier, and call the Delete method. Here is an example:
Sub Exercise()
Rows(3).Delete
End Sub
Of course, you can use either the Rows collection or the Range object to refer to the
row.
Deleting Rows
To delete a group of rows, identify them using the Range collection. Then call the
Delete method. Here is an example:
Sub Exercise()
Range("3:3, 6:6, 10:10").Delete
End Sub
Using Rows
Moving Rows
To move a group of rows, access the Range collection and identify them. Call the
Cut method. Access its Destination argument to which you will assign the rows
where you are moving. Here is an example:
Sub Exercise()
Rows("11:12").Cut Destination:=Rows("16:17")
End Sub
http://www.functionx.com/vbaexcel/Lesson16.htm
123
Previous
http://www.functionx.com/vbaexcel/Lesson16.htm
Next
124
A Cell in a Worksheet
Introduction
A spreadsheet is a series of columns and rows. These columns and rows intersect to create cells:
When Microsoft Excel starts, it creates 16,384 columns and 1,048,576 rows. As a result, a
Microsoft Excel spreadsheet has 16,384 * 1,048,576 = 17,179,869,184 cells available.
Referencing Cells
To identify a cell, you can use the Range object. In the parentheses of the Range object, pass a
string that contains the name of the cell. Here is an example that refers to the cell located as D6:
Sub Exercise()
Workbooks.Item(1).Worksheets.Item("Sheet1").Range("D6")
End Sub
To get a reference to a cell, declare a variable of type Range. To initialize the variable, identify
the cell and assign it to the variable using the Set operator. Here is an example:
Sub Exercise()
Dim Cell As Range
Set Cell = Workbooks.Item(1).Worksheets.Item("Sheet1").Range("D6")
End Sub
Cells are referred to as adjacent when they touch each other. To refer to a group of adjacent cells,
in the parentheses of the Range object, pass a string that is made of the address of the cell that
will be on one corner, followed by a colon, followed by the address of the cell that will be on the
other corner. Here is an example:
Sub Exercise()
Range("B2:H6")
End Sub
You can use this same technique to refer to one cell. To do this, use the same cell address on both
sides of the colon. Here is an example:
Sub Exercise()
Range("D4:D4")
End Sub
Instead of referring to one group of adjacent cells, you can refer to more than one group of
non-adjacent cells. To do this, pass a string to the Range object. In the string, create each range
as you want but separate them with commas. Here is an example:
Sub Exercise()
http://www.functionx.com/vbaexcel/Lesson17.htm
Range("D2:B5, F8:I14")
End Sub
125
Selecting Cells
Introduction
Before doing anything on a cell or a group of cells, you must first select it. To support cell
selection, the Range object is equipped with a method named Select. Therefore, to
programmatically select a cell, after referencing it, call the Select method. Here is an example:
Sub Exercise()
Range("D6").Select
End Sub
When you have selected a cell, it is stored in an object named Selection. You can use this object
to take an action on the cell that is currently selected.
Selecting Cells
To programmatically select a group of adjacent cells, refer to the group using the techniques we
saw earlier, then call the Select method.
To programmatically select all cells of a column, access the Columns collection and pass the
column name as a string, then call the Select method. Here is an example we saw in Lesson 9:
Sub Exercise()
Rem This selects all cells from the fourth column
Columns(4).Select
End Sub
To perform this operation using the name of a column, pass that name as argument. Here is an
example that selects all cells from Column ADH:
Sub Exercise()
Rem This selects all cells from the column labeled ADH
Columns("ADH").Select
End Sub
You can also perform this operation using the Range object. To do this, use the Range collection.
In the parentheses of the colection, enter the name of the column, followed by a colon, followed
by the same column name. Here is an example:
Sub Exercise()
Rem This selects all cells from Column G
Range("G:G").Select
End Sub
To programmatically select all cells that belong to a group of adjacent columns, in the parentheses
of the Columns collection, enter the name of the first column on one end, followed by a colon ":",
followed the name of the column that will be at the other end. Here is an example:
Sub Exercise()
Rem This selects all cells in the range of columns from Column D to Column G
Columns("D:G").Select
End Sub
To select the cells that belong to a group of non-adjacent columns, use the technique we saw
earlier to refer to non-adjacent columns, then call the Select method. Here is an example:
Sub Exercise()
Rem This selects the cells from columns B, D, and H
Range("H:H, D:D, B:B").Select
End Sub
To programmatically select all cells that belong to a row, access a row from the Rows collection,
then call the Select method. Here is an example that all cells from Row 6:
Sub Exercise()
Rows(6).Select
End Sub
You can also use the Range object. After accessing the row, call the Select method. Here is an
example that selects all cells from Row 4:
Sub Exercise()
Range("4:4").Select
End Sub
To select all cells that belong to a range of rows, refer to the range and call the Select method.
Here is an example that selects all cells that belong to the rows from 2 to 6:
Sub Exercise()
Rows("2:6").Select
End Sub
To select all cells that belong to non-adjacent rows, refer to the rows and call the Select method.
Here is an example that selects all cells belonging to Rows 3, 5, and 8:
Sub Exercise()
Range("3:3, 5:5, 8:8").Select
End Sub
http://www.functionx.com/vbaexcel/Lesson17.htm
To programmatically select cells in the same region, enter their range as a string to the Range
object, then call the Select method. Here is an example:
Sub Exercise()
Range("B2:H6").Select
End Sub
Remember that you can use the same technique to refer to one cell, thus to select a cell. Here is
an example:
Sub Exercise()
Range("D4:D4").Select
End Sub
To select more than one group of non-adjacent cells, refer to the combination as we saw earlier
and call the Select method. Here is an example:
Sub Exercise()
Range("D2:B5, F8:I14").Select
End Sub
To select all cells of a spreadsheet, you can call the Select method on the Rows collection. Here
is an example:
Sub Exercise()
Rows.Select
End Sub
Instead of the Rows collection, you can use the Columns collection instead and you would get
the same result.
When you have selected a group of cells, the group is stored in an object named Selection. You
can use this object to take a common action on all of the cells that are currently selected.
Operations on Cells
Adding Cells
We know that, to insert a column made of (vertical) cells, you can access the Columns collection,
specify an index in its parentheses, and call the Insert method. Here is an example:
Sub CreateColumn()
Columns(3).Insert
End Sub
We also know how to create a series of rows made of cells horizontally.
http://www.functionx.com/vbaexcel/Lesson17.htm
126
127
6. Click OK
7. On the Ribbon, click Stop Recording
Option Explicit
Sub CreateWorkbook()
' CreateWorkbook Macro
' This macro is used to create a workbook for the
' Georgetown Dry Cleaning Services
' Keyboard Shortcut: Ctrl+Shift+W
Rem Just in case there is anything on the
Rem worksheet, delete everything
Range("A:K").Delete
Range("1:20").Delete
Rem Create the sections and headings of the worksheet
Range("B2") = "Georgetown Dry Cleaning Services"
Range("B5") = "Order Identification"
Range("B6") = "Receipt #:"
Range("G6") = "Order Status:"
Range("B7") = "Customer Name:"
Range("G7") = "Customer Phone:"
Range("B9") = "Date Left:"
Range("G9") = "Time Left:"
Range("B10") = "Date Expected:"
Range("G10") = "Time Expected:"
Range("B11") = "Date Picked Up:"
Range("G11") = "Time Picked Up:"
Range("B13")
Range("B14")
Range("D14")
Range("E14")
Range("F14")
=
=
=
=
=
"Items to Clean"
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B15")
Range("H15")
Range("B16")
Range("B17")
Range("H17")
Range("B18")
Range("H18")
Range("I18")
Range("J18")
Range("B19")
Range("H19")
Range("B20")
Range("H20")
=
=
=
=
=
=
=
=
=
=
=
=
=
"Shirts"
"Order Summary"
"Pants"
"None"
"Cleaning Total:"
"None"
"Tax Rate:"
"5.75"
"%"
"None"
"Tax Amount:"
"None"
"Order Total:"
Rem Change the widths and heights of some columns and rows
Rem In previous lessons, we learned all these things
Range("E:E, G:G").ColumnWidth = 4
Columns("H").ColumnWidth = 14
Columns("J").ColumnWidth = 1.75
Rows("3").RowHeight = 2
http://www.functionx.com/vbaexcel/Lesson17.htm
128
Range("8:8, 12:12").RowHeight = 8
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
11. To return to Microsoft Excel, click the View Microsoft Excel button
12. To fill the worksheet, press Ctrl + Shift + W
Previous
http://www.functionx.com/vbaexcel/Lesson17.htm
Next
129
6. Click OK
7. On the Ribbon, click Stop Recording
http://www.functionx.com/vbaexcel/Lesson18.htm
=
=
=
=
=
"Items to Clean"
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B15")
Range("H15")
Range("B16")
Range("B17")
Range("H17")
Range("B18")
Range("H18")
Range("I18")
Range("J18")
Range("B19")
Range("H19")
Range("B20")
Range("H20")
=
=
=
=
=
=
=
=
=
=
=
=
=
"Shirts"
"Order Summary"
"Pants"
"None"
"Cleaning Total:"
"None"
"Tax Rate:"
"5.75"
"%"
"None"
"Tax Amount:"
"None"
"Order Total:"
Rem Change the widths and heights of some columns and rows
Rem In previous lessons, we learned all these things
Range("E:E, G:G").ColumnWidth = 4
Columns("H").ColumnWidth = 14
Columns("J").ColumnWidth = 1.75
Rows("3").RowHeight = 2
Range("8:8, 12:12").RowHeight = 8
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
11. To return to Microsoft Excel, click the View Microsoft Excel button
12. To fill the worksheet, press Ctrl + Shift + W
http://www.functionx.com/vbaexcel/Lesson18.htm
130
=
=
=
=
"Receipt #:"
"Order Status:"
"Customer Name:"
"Customer Phone:"
=
=
=
=
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B15") = "Shirts"
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
. . . No Change
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W to see the result
http://www.functionx.com/vbaexcel/Lesson18.htm
131
=
=
=
=
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B15") = "Shirts"
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
Range("H15").Font.Size = 14
. . . No Change
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W to see the result
Italic, Underline, and Strikethrough. Therefore, to grammatically specify the font style of a cell
or a group of cells, access the cell or the group of cells, access its Font object, followed by the
desired style, and assign the desired Boolean value.
http://www.functionx.com/vbaexcel/Lesson18.htm
132
133
Range("1:20").Delete
Rem Create the sections and headings of the worksheet
Range("B2") = "Georgetown Dry Cleaning Services"
Range("B2").Font.Name = "Rockwell Condensed"
Range("B2").Font.Size = 24
Range("B2").Font.Bold = True
Range("B5") = "Order Identification"
Range("B5").Font.Name = "Cambria"
Range("B5").Font.Size = 14
Range("B5").Font.Bold = True
. . . No Change
Range("B13") = "Items to
Range("B13").Font.Name =
Range("B13").Font.Size =
Range("B13").Font.Bold =
Range("B14")
Range("D14")
Range("E14")
Range("F14")
=
=
=
=
Clean"
"Cambria"
14
True
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B15") = "Shirts"
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
Range("H15").Font.Size = 14
Range("H15").Font.Bold = True
. . . No Change
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W to see the result
3. Return to Microsoft Visual Basic
Text Color
A character or text can use a color to get a better visual representation. The VBA supports colors
at different levels. To support colors, the Font object is equipped with a property named Color. To
specify the color, assign the desired color to the property. The VBA provides a (limited) list of
colors that each can be specified using a named constant. They are:
Color Name
Constant
Value
Black
vbBlack
&h00
&hFF
Red
vbRed
Green
vbGreen
&hFF00
Yellow
vbYellow
&hFFFF
Blue
vbBlue
&hFF0000
Magenta
vbMagenta
&hFF00FF
Cyan
vbCyan
&hFFFF00
White
vbWhite
&hFFFFFF
Color
Therefore, the available colors are vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta,
vbCyan, and vbWhite. These are standard colors. In reality, a color in Microsoft Windows is
represented as a value between 0 and 16,581,375 (in the next lesson, we will know where that
number comes from). This means that you can assign a positive number to the Font.Color
property and use the equivalent color.
The colors in the Font Color button are represented by a property named ThemeColor. Each one
of the colors in the Theme Colors section has an equivalent name in the VBA. If you know the
name of the color, assign it to the ThemeColor property.
As another alternative to specify a color, in the next lesson, we will see that you can use a
function named RGB to specify a color.
http://www.functionx.com/vbaexcel/Lesson18.htm
=
=
=
=
"Item"
"Unit Price"
"Qty"
"Sub-Total"
. . . No Change
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
Range("H15").Font.Size = 14
Range("H15").Font.Bold = True
Range("H15").Font.ThemeColor = 5
. . . No Change
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W to see the result
Cell Alignment
Cells Merging
To programmatically merge some cells, first select them and access the MergeCells Boolean
property. Then assign True or False depending on your intentions.
http://www.functionx.com/vbaexcel/Lesson18.htm
134
ActiveWindow.DisplayGridlines = False
End Sub
Cells Borders
The Line Style of a Border
A cell appears as a rectangular box with borders and a background. To programmatically
control the borders of a cell or a group of cells, refer to the cell or the group of cells and
access its Borders object. This object is accessed as an indexed property. Here is an
example:
Range("B2").Borders()
In the parentheses of the Borders property, specify the border you want to change. The
primary available values are: xlEdgeBottom, xlEdgeTop, xlEdgeLeft, and xlEdgeRight.
Sometimes you may have selected a group of cells and you want to take an action on the
line(s) between (among) them. To support this, the Borders property can take an index
named xlInsideVertical for a vertical border between two cells or an index named
xlInsideHorizontal for a horizontal border between the cells.
After specifying the border you want to work on, you must specify the type of characteristic
you want to change. For example, you can specify the type of line you want the border to
show. To support this, the Borders object is equipped with a property named LineStyle. To
specify the type of line you want the border to display, you can assign a value to the
LineStyle property. The available values are xlContinuous, xlDash, xlDashDot,
xlDashDotDot, xlDot, xlDouble, xlSlantDashDot, and xlLineStyleNone. Therefore, you
can assign any of these values to the property. To assist you with this, you can type
LineStyle followed by a period and select the desired value from the list that appears:
http://www.functionx.com/vbaexcel/Lesson18.htm
135
=
=
=
=
Clean"
"Cambria"
14
True
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B14:F14").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeTop).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("C14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B15") = "Shirts"
Range("B15").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
Range("H15").Font.Size = 14
Range("H15").Font.Bold = True
Range("B16") = "Pants"
Range("B16").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B17") = "None"
http://www.functionx.com/vbaexcel/Lesson18.htm
136
Range("B17").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("H17") = "Cleaning Total:"
Range("I17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B18") = "None"
Range("B18").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("H18") = "Tax Rate:"
Range("I18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I18") = "5.75"
Range("J18") = "%"
Range("B19") = "None"
Range("B19").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("H19") = "Tax Amount:"
Range("I19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B20") = "None"
Range("B20").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("C15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B14:C14").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B15:C15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D15:F15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B16:C16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D16:F16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B17:C17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D17:F17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B18:C18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D18:F18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B19:C19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D19:F19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B20:F20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("H20") = "Order Total:"
Range("I20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Rem Change the widths and heights of some columns and rows
Rem In previous lessons, we learned all these things
Range("E:E, G:G").ColumnWidth = 4
Columns("H").ColumnWidth = 14
Columns("J").ColumnWidth = 1.75
Rows("3").RowHeight = 2
Range("8:8, 12:12").RowHeight = 8
Rem Merge the cells H15, I15, H16, and I16
Range("H15:I16").MergeCells = True
Rem Align the merged text to the left
Range("H15:H16").VerticalAlignment = xlCenter
Range("H16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
http://www.functionx.com/vbaexcel/Lesson18.htm
137
Clean"
"Cambria"
14
True
Range("B14") = "Item"
http://www.functionx.com/vbaexcel/Lesson18.htm
138
139
http://www.functionx.com/vbaexcel/Lesson18.htm
Range("D16").Borders(xlEdgeRight).Weight = xlHairline
Range("E16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E16").Borders(xlEdgeRight).Weight = xlHairline
Range("F16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F16").Borders(xlEdgeRight).Weight = xlThin
Range("B17:C17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B17:C17").Borders(xlEdgeBottom).Weight = xlThin
Range("D17:F17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D17:F17").Borders(xlEdgeBottom).Weight = xlHairline
Range("D17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D17").Borders(xlEdgeRight).Weight = xlHairline
Range("E17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E17").Borders(xlEdgeRight).Weight = xlHairline
Range("F17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F17").Borders(xlEdgeRight).Weight = xlThin
Range("B18:C18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B18:C18").Borders(xlEdgeBottom).Weight = xlThin
Range("D18:F18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D18:F18").Borders(xlEdgeBottom).Weight = xlHairline
Range("D18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D18").Borders(xlEdgeRight).Weight = xlHairline
Range("E18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E18").Borders(xlEdgeRight).Weight = xlHairline
Range("F18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F18").Borders(xlEdgeRight).Weight = xlThin
Range("B19:C19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B19:C19").Borders(xlEdgeBottom).Weight = xlThin
Range("D19:F19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D19:F19").Borders(xlEdgeBottom).Weight = xlHairline
Range("D19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D19").Borders(xlEdgeRight).Weight = xlHairline
Range("E19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E19").Borders(xlEdgeRight).Weight = xlHairline
Range("F19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F19").Borders(xlEdgeRight).Weight = xlThin
Range("B20:F20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B20:F20").Borders(xlEdgeBottom).Weight = xlThin
Range("D20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D20").Borders(xlEdgeRight).Weight = xlHairline
Range("E20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E20").Borders(xlEdgeRight).Weight = xlHairline
Range("F20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F20").Borders(xlEdgeRight).Weight = xlThin
Range("H20") = "Order Total:"
Range("I20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I20").Borders(xlEdgeBottom).Weight = xlHairline
Rem Change the widths and heights of some columns and rows
Rem In previous lessons, we learned all these things
Range("E:E, G:G").ColumnWidth = 4
Columns("H").ColumnWidth = 14
Columns("J").ColumnWidth = 1.75
Rows("3").RowHeight = 2
Range("8:8, 12:12").RowHeight = 8
Rem Merge the cells H15, I15, H16, and I16
Range("H15:I16").MergeCells = True
Rem Align the merged text to the left
Range("H15:H16").VerticalAlignment = xlCenter
Range("H16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("H16:I16").Borders(xlEdgeBottom).Weight = xlMedium
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W to see the result
http://www.functionx.com/vbaexcel/Lesson18.htm
140
141
142
http://www.functionx.com/vbaexcel/Lesson18.htm
Range("B14")
Range("D14")
Range("E14")
Range("F14")
=
=
=
=
143
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B14:F14").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeLeft).Weight = xlThin
Range("B14:F14").Borders(xlEdgeTop).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeTop).Weight = xlThin
Range("B14:F14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeRight).Weight = xlThin
Range("B14:F14").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeBottom).Weight = xlThin
Range("C14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C14").Borders(xlEdgeRight).Weight = xlThin
Range("D14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D14").Borders(xlEdgeRight).Weight = xlThin
Range("E14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E14").Borders(xlEdgeRight).Weight = xlThin
Range("B15") = "Shirts"
Range("B15").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B15").Borders(xlEdgeLeft).Weight = xlThin
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
Range("H15").Font.Size = 14
Range("H15").Font.Bold = True
Range("H15").Font.ThemeColor = 5
Range("B16") = "Pants"
Range("B16").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B16").Borders(xlEdgeLeft).Weight = xlThin
Range("B17") = "None"
Range("B17").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B17").Borders(xlEdgeLeft).Weight = xlThin
Range("H17") = "Cleaning Total:"
Range("I17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I17").Borders(xlEdgeBottom).Weight = xlHairline
Range("B18") = "None"
Range("B18").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B18").Borders(xlEdgeLeft).Weight = xlThin
Range("H18") = "Tax Rate:"
Range("I18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I18").Borders(xlEdgeBottom).Weight = xlHairline
Range("I18") = "5.75"
Range("J18") = "%"
Range("B19") = "None"
Range("B19").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B19").Borders(xlEdgeLeft).Weight = xlThin
Range("H19") = "Tax Amount:"
Range("I19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I19").Borders(xlEdgeBottom).Weight = xlHairline
Range("B20") = "None"
Range("B20").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B20").Borders(xlEdgeLeft).Weight = xlThin
Range("C15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C15").Borders(xlEdgeRight).Weight = xlThin
Range("C16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C16").Borders(xlEdgeRight).Weight = xlThin
Range("C17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C17").Borders(xlEdgeRight).Weight = xlThin
Range("C18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C18").Borders(xlEdgeRight).Weight = xlThin
Range("C19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C19").Borders(xlEdgeRight).Weight = xlThin
Range("C20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C20").Borders(xlEdgeRight).Weight = xlThin
Range("B14:C14").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B14:C14").Borders(xlEdgeBottom).Weight = xlThin
Range("B15:C15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B15:C15").Borders(xlEdgeBottom).Weight = xlThin
Range("D15:F15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D15:F15").Borders(xlEdgeBottom).Weight = xlHairline
Range("D15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D15").Borders(xlEdgeRight).Weight = xlHairline
Range("E15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E15").Borders(xlEdgeRight).Weight = xlHairline
Range("F15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F15").Borders(xlEdgeRight).Weight = xlThin
Range("B16:C16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B16:C16").Borders(xlEdgeBottom).Weight = xlThin
Range("D16:F16").Borders(xlEdgeBottom).LineStyle = xlContinuous
http://www.functionx.com/vbaexcel/Lesson18.htm
Range("D16:F16").Borders(xlEdgeBottom).Weight = xlHairline
Range("D16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D16").Borders(xlEdgeRight).Weight = xlHairline
Range("E16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E16").Borders(xlEdgeRight).Weight = xlHairline
Range("F16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F16").Borders(xlEdgeRight).Weight = xlThin
Range("B17:C17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B17:C17").Borders(xlEdgeBottom).Weight = xlThin
Range("D17:F17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D17:F17").Borders(xlEdgeBottom).Weight = xlHairline
Range("D17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D17").Borders(xlEdgeRight).Weight = xlHairline
Range("E17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E17").Borders(xlEdgeRight).Weight = xlHairline
Range("F17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F17").Borders(xlEdgeRight).Weight = xlThin
Range("B18:C18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B18:C18").Borders(xlEdgeBottom).Weight = xlThin
Range("D18:F18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D18:F18").Borders(xlEdgeBottom).Weight = xlHairline
Range("D18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D18").Borders(xlEdgeRight).Weight = xlHairline
Range("E18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E18").Borders(xlEdgeRight).Weight = xlHairline
Range("F18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F18").Borders(xlEdgeRight).Weight = xlThin
Range("B19:C19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B19:C19").Borders(xlEdgeBottom).Weight = xlThin
Range("D19:F19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D19:F19").Borders(xlEdgeBottom).Weight = xlHairline
Range("D19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D19").Borders(xlEdgeRight).Weight = xlHairline
Range("E19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E19").Borders(xlEdgeRight).Weight = xlHairline
Range("F19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F19").Borders(xlEdgeRight).Weight = xlThin
Range("B20:F20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B20:F20").Borders(xlEdgeBottom).Weight = xlThin
Range("D20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D20").Borders(xlEdgeRight).Weight = xlHairline
Range("E20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E20").Borders(xlEdgeRight).Weight = xlHairline
Range("F20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F20").Borders(xlEdgeRight).Weight = xlThin
Range("H20") = "Order Total:"
Range("I20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I20").Borders(xlEdgeBottom).Weight = xlHairline
Rem Change the widths and heights of some columns and rows
Rem In previous lessons, we learned all these things
Range("E:E, G:G").ColumnWidth = 4
Columns("H").ColumnWidth = 14
Columns("J").ColumnWidth = 1.75
Rows("3").RowHeight = 2
Range("8:8, 12:12").RowHeight = 8
Rem Merge the cells H15, I15, H16, and I16
Range("H15:I16").MergeCells = True
Rem Align the merged text to the left
Range("H15:H16").VerticalAlignment = xlBottom
Range("H16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("H16:I16").Borders(xlEdgeBottom).Weight = xlMedium
Range("H16:I16").Borders(xlEdgeBottom).ThemeColor = 5
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W to see the result
http://www.functionx.com/vbaexcel/Lesson18.htm
144
145
Previous
http://www.functionx.com/vbaexcel/Lesson18.htm
Next
146
Introduction to Expressions
An expression is one or more symbols combined with one or more values to create another value.
For example, +16 is an expression that creates the positive value 16. Most expressions that we
know are made of arithmetic calculations. An example is 422.82 * 15.55.
To add an expression to a selected cell, assign it to the ActiveCell object. Here is an example:
Sub Exercise()
ActiveCell = 422.82 * 15.5
End Sub
Sub CreateWorkbook()
'
' CreateWorkbook Macro
' This macro is used to create a workbook for the
' Georgetown Dry Cleaning Services
'
' Keyboard Shortcut: Ctrl+Shift+W
'
Rem Just in case there is anything on the
Rem worksheet, delete everything
Range("A:K").Delete
Range("1:20").Delete
Rem Create the sections and headings of the worksheet
Range("B2") = "Georgetown Dry Cleaning Services"
Range("B2").Font.Name = "Rockwell Condensed"
Range("B2").Font.Size = 24
Range("B2").Font.Bold = True
Range("B2").Font.Color = vbBlue
Range("B3:J3").Interior.ThemeColor = xlThemeColorLight2
Range("B5") = "Order Identification"
Range("B5").Font.Name = "Cambria"
http://www.functionx.com/vbaexcel/Lesson19.htm
Range("B5").Font.Size = 14
Range("B5").Font.Bold = True
Range("B5").Font.ThemeColor = 5
Rem To draw a thick line, change the bottom
Rem borders of the cells from B5 to J5
Range("B5:J5").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B5:J5").Borders(xlEdgeBottom).Weight = xlMedium
Range("B5:J5").Borders(xlEdgeBottom).ThemeColor = 5
Range("B6") = "Receipt #:"
Range("D6:F6").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D6:F6").Borders(xlEdgeBottom).Weight = xlHairline
Range("G6") = "Order Status:"
Range("I6:J6").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I6:J6").Borders(xlEdgeBottom).Weight = xlHairline
Range("B7") = "Customer Name:"
Range("D7:F7").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D7:F7").Borders(xlEdgeBottom).Weight = xlHairline
Range("G7") = "Customer Phone:"
Range("I7:J7").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I7:J7").Borders(xlEdgeBottom).Weight = xlHairline
Rem To draw a thick line, change the bottom
Rem borders of the cells from B5 to J5
Range("B8:J8").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B8:J8").Borders(xlEdgeBottom).Weight = xlThin
Range("B9") = "Date Left:"
Range("D9:F9").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D9:F9").Borders(xlEdgeBottom).Weight = xlHairline
Range("G9") = "Time Left:"
Range("I9:J9").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I9:J9").Borders(xlEdgeBottom).Weight = xlHairline
Range("B10") = "Date Expected:"
Range("D10:F10").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D10:F10").Borders(xlEdgeBottom).Weight = xlHairline
Range("G10") = "Time Expected:"
Range("I10:J10").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I10:J10").Borders(xlEdgeBottom).Weight = xlHairline
Range("B11") = "Date Picked Up:"
Range("D11:F11").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D11:F11").Borders(xlEdgeBottom).Weight = xlHairline
Range("G11") = "Time Picked Up:"
Range("I11:J11").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I11:J11").Borders(xlEdgeBottom).Weight = xlHairline
Rem To draw a thick line, change the bottom
Rem borders of the cells from B5 to J5
Range("B12:J12").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B12:J12").Borders(xlEdgeBottom).Weight = xlMedium
Range("B12:J12").Borders(xlEdgeBottom).ThemeColor = 5
Range("B13") = "Items to Clean"
Range("B13").Font.Name = "Cambria"
Range("B13").Font.Size = 14
Range("B13").Font.Bold = True
Range("B13").Font.ThemeColor = 5
Range("B14")
Range("D14")
Range("E14")
Range("F14")
=
=
=
=
"Item"
"Unit Price"
"Qty"
"Sub-Total"
Range("B14:F14").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeLeft).Weight = xlThin
Range("B14:F14").Borders(xlEdgeTop).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeTop).Weight = xlThin
Range("B14:F14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeRight).Weight = xlThin
Range("B14:F14").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B14:F14").Borders(xlEdgeBottom).Weight = xlThin
Range("C14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C14").Borders(xlEdgeRight).Weight = xlThin
Range("D14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D14").Borders(xlEdgeRight).Weight = xlThin
Range("E14").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E14").Borders(xlEdgeRight).Weight = xlThin
Range("B15") = "Shirts"
Range("B15").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B15").Borders(xlEdgeLeft).Weight = xlThin
Range("H15") = "Order Summary"
Range("H15").Font.Name = "Cambria"
Range("H15").Font.Size = 14
Range("H15").Font.Bold = True
Range("H15").Font.ThemeColor = 5
http://www.functionx.com/vbaexcel/Lesson19.htm
147
Range("B16") = "Pants"
Range("B16").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B16").Borders(xlEdgeLeft).Weight = xlThin
Range("B17") = "None"
Range("B17").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B17").Borders(xlEdgeLeft).Weight = xlThin
Range("H17") = "Cleaning Total:"
Range("I17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I17").Borders(xlEdgeBottom).Weight = xlHairline
Range("B18") = "None"
Range("B18").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B18").Borders(xlEdgeLeft).Weight = xlThin
Range("H18") = "Tax Rate:"
Range("I18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I18").Borders(xlEdgeBottom).Weight = xlHairline
Range("I18") = "5.75"
Range("J18") = "%"
Range("B19") = "None"
Range("B19").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B19").Borders(xlEdgeLeft).Weight = xlThin
Range("H19") = "Tax Amount:"
Range("I19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I19").Borders(xlEdgeBottom).Weight = xlHairline
Range("B20") = "None"
Range("B20").Borders(xlEdgeLeft).LineStyle = xlContinuous
Range("B20").Borders(xlEdgeLeft).Weight = xlThin
Range("C15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C15").Borders(xlEdgeRight).Weight = xlThin
Range("C16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C16").Borders(xlEdgeRight).Weight = xlThin
Range("C17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C17").Borders(xlEdgeRight).Weight = xlThin
Range("C18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C18").Borders(xlEdgeRight).Weight = xlThin
Range("C19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C19").Borders(xlEdgeRight).Weight = xlThin
Range("C20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("C20").Borders(xlEdgeRight).Weight = xlThin
Range("B14:C14").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B14:C14").Borders(xlEdgeBottom).Weight = xlThin
Range("B15:C15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B15:C15").Borders(xlEdgeBottom).Weight = xlThin
Range("D15:F15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D15:F15").Borders(xlEdgeBottom).Weight = xlHairline
Range("D15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D15").Borders(xlEdgeRight).Weight = xlHairline
Range("E15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E15").Borders(xlEdgeRight).Weight = xlHairline
Range("F15").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F15").Borders(xlEdgeRight).Weight = xlThin
Range("B16:C16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B16:C16").Borders(xlEdgeBottom).Weight = xlThin
Range("D16:F16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D16:F16").Borders(xlEdgeBottom).Weight = xlHairline
Range("D16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D16").Borders(xlEdgeRight).Weight = xlHairline
Range("E16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E16").Borders(xlEdgeRight).Weight = xlHairline
Range("F16").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F16").Borders(xlEdgeRight).Weight = xlThin
Range("B17:C17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B17:C17").Borders(xlEdgeBottom).Weight = xlThin
Range("D17:F17").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D17:F17").Borders(xlEdgeBottom).Weight = xlHairline
Range("D17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D17").Borders(xlEdgeRight).Weight = xlHairline
Range("E17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E17").Borders(xlEdgeRight).Weight = xlHairline
Range("F17").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F17").Borders(xlEdgeRight).Weight = xlThin
Range("B18:C18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B18:C18").Borders(xlEdgeBottom).Weight = xlThin
Range("D18:F18").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D18:F18").Borders(xlEdgeBottom).Weight = xlHairline
Range("D18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D18").Borders(xlEdgeRight).Weight = xlHairline
Range("E18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E18").Borders(xlEdgeRight).Weight = xlHairline
Range("F18").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F18").Borders(xlEdgeRight).Weight = xlThin
Range("B19:C19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B19:C19").Borders(xlEdgeBottom).Weight = xlThin
Range("D19:F19").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("D19:F19").Borders(xlEdgeBottom).Weight = xlHairline
http://www.functionx.com/vbaexcel/Lesson19.htm
148
Range("D19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D19").Borders(xlEdgeRight).Weight = xlHairline
Range("E19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E19").Borders(xlEdgeRight).Weight = xlHairline
Range("F19").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F19").Borders(xlEdgeRight).Weight = xlThin
Range("B20:F20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("B20:F20").Borders(xlEdgeBottom).Weight = xlThin
Range("D20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("D20").Borders(xlEdgeRight).Weight = xlHairline
Range("E20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("E20").Borders(xlEdgeRight).Weight = xlHairline
Range("F20").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("F20").Borders(xlEdgeRight).Weight = xlThin
Range("H20") = "Order Total:"
Range("I20").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("I20").Borders(xlEdgeBottom).Weight = xlHairline
Rem Change the widths and heights of some columns and rows
Rem In previous lessons, we learned all these things
Range("E:E, G:G").ColumnWidth = 4
Columns("H").ColumnWidth = 14
Columns("J").ColumnWidth = 1.75
Rows("3").RowHeight = 2
Range("8:8, 12:12").RowHeight = 8
Rem Merge the cells H15, I15, H16, and I16
Range("H15:I16").MergeCells = True
Rem Align the merged text to the left
Range("H15:H16").VerticalAlignment = xlBottom
Range("H16").Borders(xlEdgeBottom).LineStyle = xlContinuous
Range("H16:I16").Borders(xlEdgeBottom).Weight = xlMedium
Range("H16:I16").Borders(xlEdgeBottom).ThemeColor = 5
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
10. To return to Microsoft Excel, click the View Microsoft Excel button
11. To fill the worksheet, press Ctrl + Shift + W
Introduction to Formulas
A formula is another name for an expression. It combines one or more values, one or more
variables, to an operator, to produce a new value. This also means that you use the same
approach or building an expression when creating a formula.
To assist you with assigning the result of a formula to a cell or a group of cells, the Range class is
equipped with a property named Formula. This property is of type Variant, which means its value
can be anything, not necessarily a number. After accessing the Formula property, you can assign
whatever value, expression, or formula you want to it. Here are examples:
Sub Exercise()
Rem Using the Formula property to assign a string to the active cell
ActiveCell.Formula = "Weekly Salary:"
Rem Using the Formula property to assign an expression to cell B2
Range("B2").Formula = 24.5 * 42.5
Rem Using the Formula property to assign
Rem the same string to a group of cells
Range("C2:F5, B8:D12").Formula = "Antoinette"
End Sub
If you are creating a worksheet that would be used on computers of different languages, use
FormulaLocal instead. The FormulaLocal property is equipped to adapt to a different
language-based version of Microsoft Excel when necessary.
Besides Formula, the Range class is also equipped with a property named FormulaR1C1. Its
functionality is primarily the same as Formula. Here are examples:
Sub Exercise()
Rem Using the Formula property to assign a string to the active cell
ActiveCell.FormulaR1C1 = "Weekly Salary:"
Rem Using the Formula property to assign an expression to cell B2
Range("B2").FormulaR1C1 = 24.5 * 42.5
Rem Using the Formula property to assign
Rem the same string to a group of cells
Range("C2:F5, B8:D12").FormulaR1C1 = "Antoinette"
End Sub
If you are creating the worksheet for various languages, use FormulaR1C1Local instead.
http://www.functionx.com/vbaexcel/Lesson19.htm
149
Sub CalculateOrder()
'
' CreateWorkbook Macro
'
' Keyboard Shortcut: Ctrl+Shift+C
'
Rem Calculate the sub-total of each category of items as:
Rem SubTotal = Unit Price * Quantity
Rem And display the total in the equivalent F cell
Range("F15").Formula = Range("D15") * Range("E15")
Range("F16").Formula = Range("D16") * Range("E16")
Range("F17").Formula = Range("D17") * Range("E17")
Range("F18").Formula = Range("D18") * Range("E18")
Range("F19").Formula = Range("D19") * Range("E19")
Range("F20").Formula = Range("D20") * Range("E20")
Rem Retrieve the values of the cleaning total and the tax rate
Rem Use them to calculate the amount of tax
Range("I19").Formula = Range("I17") * Range("I18") / 100
Rem Calculate the total order by adding
Rem the cleaning total to the tax amount
Range("I20").Formula = Range("I17") + Range("I19")
End Sub
http://www.functionx.com/vbaexcel/Lesson19.htm
150
151
After specifying the function you want to use, because it is a function, you must include the
parentheses. In the parentheses, type the necessary argument(s). Here is an example:
Private Sub cmdCreate_Click()
txtValue.Text = Application.WorksheetFunction.Sum(Range("D4:D8"))
End Sub
Conversion Functions
You may recall that when studying data types, we saw that each had a corresponding function
used to convert a string value or an expression to that type. As a reminder, the general syntax of
the conversion functions is:
ReturnType = FunctionName(Expression)
The Expression could be of any kind. For example, it could be a string or expression that would
produce a value such as the result of a calculation. The conversion function would take such a
value, string, or expression and attempt to convert it. If the conversion is successful, the function
would return a new value that is of the type specified by the ReturnType in our syntax.
The conversion functions are as follows:
Function
Name
CBool
Boolean
CByte
Byte
CDbl
Double
CDec
Decimal
CInt
Integer
CLng
Long
CObj
Object
CSByte
SByte
CShort
Short
Single
CSng
CUInt
UInt
CULng
ULong
CUShort
UShort
Sub CalculateOrder()
'
' CalculateOrder Macro
'
' Keyboard Shortcut: Ctrl+Shift+C
Rem Calculate the sub-total of each category of items as:
Rem SubTotal = Unit Price * Quantity
Rem And display the total in the equivalent F cell
Range("F15").Formula = CDbl(Range("D15")) * CInt(Range("E15"))
Range("F16").Formula = CDbl(Range("D16")) * CInt(Range("E16"))
Range("F17").Formula = CDbl(Range("D17")) * CInt(Range("E17"))
Range("F18").Formula = CDbl(Range("D18")) * CInt(Range("E18"))
Range("F19").Formula = CDbl(Range("D19")) * CInt(Range("E19"))
Range("F20").Formula = CDbl(Range("D20")) * CInt(Range("E20"))
Rem Retrieve the values of the cleaning total and the tax rate
Rem Use them to calculate the amount of tax
Range("I19").Formula = CDbl(Range("I17")) * CDbl(Range("I18")) / 100
Rem Calculate the total order by adding the
Rem cleaning total to the tax amount
Range("I20").Formula = CDbl(Range("I17")) + CDbl(Range("I19"))
http://www.functionx.com/vbaexcel/Lesson19.htm
152
End Sub
Specifying a Color
To assist you with specifying the color of anything, the VBA is equipped with a function named
RGB. Its syntax is:
Function RGB(RedValue As Byte, GreenValue As Byte, BlueValue As Byte) As long
This function takes three arguments and each must hold a value between 0 and 255. The first
argument represents the ratio of red of the color. The second argument represents the green ratio
of the color. The last argument represents the blue of the color. After the function has been
called, it produces a number whose maximum value can be 255 * 255 * 255 = 16,581,375, which
represents a color.
Sub CreateWorkbook()
'
' CreateWorkbook Macro
'
' Keyboard Shortcut: Ctrl+Shift+E
'
. . . No Change
Rem Change the background color of cells F15 to F20 to a light blue
Range("F15:F20").Interior.Color = RGB(210, 225, 250)
Rem Change the background color of cells I17 to I20 to a dark blue
Range("I17:I20").Interior.Color = RGB(5, 65, 165)
Rem Change the text color of cells I17 to I20 to a dark blue
Range("I17:I20").Font.Color = RGB(255, 255, 195)
Rem Hide the gridlines
ActiveWindow.DisplayGridlines = False
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + W
3. Press Ctrl + Shift + C to see the result
http://www.functionx.com/vbaexcel/Lesson19.htm
To use the SUM() function visually, on the Ribbon, in the Home tab, the Editing section is
equipped with a button called the AutoSum
Sub CalculateOrder()
'
' CalculateOrder Macro
'
' Keyboard Shortcut: Ctrl+Shift+C
'
Rem Calculate the sub-total of each category of items as:
Rem SubTotal = Unit Price * Quantity
Rem And display the total in the equivalent F cell
Range("F15").Formula = CDbl(Range("D15")) * CInt(Range("E15"))
Range("F16").Formula = CDbl(Range("D16")) * CInt(Range("E16"))
Range("F17").Formula = CDbl(Range("D17")) * CInt(Range("E17"))
Range("F18").Formula = CDbl(Range("D18")) * CInt(Range("E18"))
Range("F19").Formula = CDbl(Range("D19")) * CInt(Range("E19"))
Range("F20").Formula = CDbl(Range("D20")) * CInt(Range("E20"))
Rem Use the SUM() function to calculate the sum of
Rem cells F15 to F20 and display the result in cell J17
Range("I17").Formula = "=SUM(F15:F20)"
Rem Retrieve the values of the cleaning total and the tax rate
Rem Use them to calculate the amount of tax
Range("I19").Formula = CDbl(Range("I17")) * CDbl(Range("I18")) / 100
Rem Calculate the total order by adding the
Rem cleaning total to the tax amount
Range("I20").Formula = CDbl(Range("I17")) + CDbl(Range("I19"))
End Sub
2. Return to Microsoft Excel and press Ctrl + Shift + C to see the result
3. Enter the following values in the worksheet:
Receipt #:
1001
Order Status:
Processing
Customer Name:
Raymond Fuqua
Customer Phone:
(140) 173-9024
Date Left:
12/19/2008
Time Left:
09:42 AM
Date Expected:
12/22/2008
Time Expected:
08:00 AM
Unit Price
Qty
Shirts
1.25
Pants
1.95
Jacket
4.50
4. Click cell A1
http://www.functionx.com/vbaexcel/Lesson19.htm
153
154
http://www.functionx.com/vbaexcel/Lesson19.htm
155
To get the absolute value of a number, you can use either the Microsoft Excel's ABS() or the
VBA's Abs() function. Their syntaxes are:
Function ABS(number) As Number
Function Abs(number) As Number
This function takes one argument. The argument must be a number or an expression convertible
to a number:
If the argument is a positive number, the function returns it
If the argument is zero, the function returns 0
If the argument is a negative number, the function is returns its equivalent positive value
If the value of the argument is a decimal number, the function returns only the integral part.
Here is an example
Sub Exercise()
Dim Number As Double
Number = 7942.225 * 202.46
ActiveCell = MsgBox(Int(Number), vbOKOnly, "Exercise")
End Sub
This would produce:
This function always returns the integral part only, even if you ask it to return a floatingpoint-based value. Here is an example:
Sub Exercise()
Dim Number As Single
Number = 286345.9924
ActiveCell = MsgBox(Int(Number), vbOKOnly, "Exercise")
End Sub
This would produce:
http://www.functionx.com/vbaexcel/Lesson19.htm
Although Microsoft Excel displays all numbers right aligned, as a smart financial and business
application, it can distinguish between different types of numbers. It can recognize a date, a
currency, or a percentage values, but the computer wants you to specify the way numbers should
be displayed, giving you the ability to decide what a particular number represents, not because
the software cannot recognize a number, but because a value can represent different things to
different people in different scenarios. For example 1.5 might represent a half teaspoon in one
spreadsheet while the same 1.5 would represent somebody's age, another spreadsheet's
percentage, or etc.
Formatting a Number
To visually specify that you want a cell to display its numeric value with the comma delimiter,
click the cell to give it focus. Then, in the Home tab of the Ribbon, in the Number section, click the
Comma Style button
easier to read.
. The thousand numbers would display with a comma sign which makes it
To visually control the number of decimal values on the right side of the comma, in the Number
section of the Ribbon:
You can click the Decrease Decimal button
To programmatically specify that you want a cell to display the comma style of number, assign the
"Comma" string to the Style property of the Range class. Here is an example:
Sub SpecifyComma()
ActiveCell.Style = "Comma"
End Sub
Alternatively
, to programmatically control how the number should display, you can pass the second argument to
the Format() function. To produce the number in a general format, you can pass the second
argument as "g", "G", "f", or "F" .
To display the number with a decimal separator, pass the second argument as "n", "N", or
"Standard". Here is an example:
Sub Exercise()
Dim Number As Double
Number = 20502.48
ActiveCell = Format(Number, "STANDARD")
End Sub
An alternative to get this format is to call a function named FormatNumber. Its syntax is:
Function FormatNumber(
ByVal Expression As Variant,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As Integer,
Optional ByVal UseParensForNegativeNumbers As Integer,
http://www.functionx.com/vbaexcel/Lesson19.htm
156
157
Only the first argument is required and it represents the value to display. If you pass only this
argument, you get the same format as the Format() function called with the Standard option.
Here is an example:
Sub Exercise()
Dim Number As Double
Number = 20502.48
ActiveCell = FormatNumber(Number)
End Sub
This would produce the same result as above.
If you call the Format() function with the Standard option, it would consider only the number of
digits on the right side of the decimal separator. If you want to display more digits than the
number actually has, call the FormatNumber() function and pass a second argument with the
desired number. Here is an example:
Sub Exercise()
Dim Number As Double
Number = 20502.48
ActiveCell = FormatNumber(Number, 4)
End Sub
In the same way, if you want the number to display with less numbers on the right side of the
decimal separator, specify that number.
on the Ribbon to visually control the
We saw that you could click the Decrease Decimal button
number of decimal values on the right side of the comma and you could continuously click that
button to decrease the number of digits. Of course, you can also exercise this control
programmatically.
You can call the Format() function to format the number with many more options. To represent
the integral part of a number, you use the # sign. To specify the number of digits to display on
the right side of the decimal separator, type a period on the right side of # followed by the
number of 0s representing each decimal place. Here is an example:
Sub Exercise()
Dim Number As Double
Number = 20502.48
ActiveCell = Format(Number, "#.00000")
End Sub
The five 0s on the right side of the period indicate that you want to display 5 digits on the right
side of the period. You can enter as many # signs as you want; it would not change anything.
Here is an example:
Sub Exercise()
Dim Number As Double
Number = 20502.48
ActiveCell = Format(Number, "##########.00000")
End Sub
This would produce the same result as above. To specify that you want to display the decimal
separator, include its character between the # signs. Here is an example:
Sub Exercise()
Dim Number As Double
Number = 20502.48
ActiveCell = Format(Number, "###,#######.00000")
End Sub
You can include any other character or symbol you want in the string to be part of the result, but
you should include such a character only at the beginning or the end of the string, otherwise the
interpreter might give you an unexpected result.
Sub CreateWorkbook()
'
' CreateWorkbook Macro
'
' Keyboard Shortcut: Ctrl+Shift+W
'
. . . No Change
Rem Format the values in the unit prices
Range("D15").Style = "Comma"
Range("D16").Style = "Comma"
Range("D17").Style = "Comma"
Range("D18").Style = "Comma"
Range("D19").Style = "Comma"
Range("D20").Style = "Comma"
http://www.functionx.com/vbaexcel/Lesson19.htm
158
1001
Order Status:
Processing
Customer Name:
Raymond Fuqua
Customer Phone:
(140) 173-9024
Date Left:
12/19/2008
Time Left:
09:42 AM
Date Expected:
12/22/2008
Time Expected:
08:00 AM
Unit Price
Qty
Shirts
1.25
Pants
1.95
Jacket
4.50
4. Click cell A1
http://www.functionx.com/vbaexcel/Lesson19.htm
159
To visually that a c
ell should display its number as currency, in the Number section of the Ribbon, click the Currency
Style button
To programmatically specify that you want a cell to display its value with the currency style,
assign the "Currency" string to the Style property of the Range class. Here is an example:
Sub SpecifyComma()
ActiveCell.Style = "Currency"
http://www.functionx.com/vbaexcel/Lesson19.htm
End Sub
160
Alternatively, to programmatically display the currency symbol in the result of a cell or a text box
of a form, you can simply add it as part of the second argument to the Format() function. Here is
an example:
Sub Exercise()
Dim Number As Double
Number = 205.5
ActiveCell = Format(Number, "$###,#######.00")
End Sub
Fortunately, there are more professional options. Besides the Format() function, to support
currency formatting of a number, the Visual Basic language provides the FormatCurrency()
function. Its syntax is:
Function FormatCurrency(
ByVal Expression As Variant,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As Integer = -2,
Optional ByVal UseParensForNegativeNumbers As Integer = -2,
Optional ByVal GroupDigits As Integer = -2
) As String
Only the first argument is required. It is the value that needs to be formatted. Here is an
example:
Sub Exercise()
Dim UnitPrice As Double
UnitPrice = 1450.5
ActiveCell = FormatCurrency(UnitPrice)
End Sub
Notice that, by default, the FormatCurrency() function is equipped to display the currency
symbol (which, in US English is, the $ sign), the decimal separator (which in US English is the
comma), and two decimal digits. If you want to control how many decimal digits are given to the
result, pass a second argument as an integer. Here is an example:
Sub Exercise()
Dim UnitPrice As Double
UnitPrice = 1450.5
ActiveCell = FormatCurrency(UnitPrice, 4)
End Sub
Instead of calling the FormatCurrency() function to format a number to currency, you can use
the Format() function. If you do, pass it a second argument as "Currency", "c", or "C". Here is
an example:
Sub Exercise()
Dim CarPrice As Double
CarPrice = 42790
ActiveCell = Format(CarPrice, "Currency")
End Sub
To programmatically use a percentage number in a cell or the control of a form, you can use the
Format() function. Besides the Format() function, to support percent values, the Visual Basic
language provides a function named FormatPercent. Its syntax is:
Function FormatPercent(
ByVal Expression As Variant,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As Integer = -2,
Optional ByVal UseParensForNegativeNumbers As Integer = -2,
Optional ByVal GroupDigits As Integer = -2
) As String
Only the first argument is required and it is the number that needs to be formatted. When calling
this function, pay attention to the number you provide as argument. If the number represents a
percentage value as a fraction of 0 to 1, make sure you provide it as such. An example would be
0.25. In this case, the Visual Basic interpreter would multiply the value by 100 to give the result.
Here is an example:
Sub Exercise()
Dim DiscountRate As Double
DiscountRate = 0.25
ActiveCell = FormatPercent(DiscountRate)
End Sub
http://www.functionx.com/vbaexcel/Lesson19.htm
If you pass the value in the hundreds, the interpreter would still multiply it by 100. Although it is
not impossible to get a percentage value in the hundreds or thousands, you should make sure
that's the type of value you mean to get.
161
Besides the FormatPercent() function, to format a number to its percentage equivalent, you can
call the Format() function and pass the second argument as "Percent", "p", or "P". Here is an
example:
Sub Exercise()
Dim DiscountRate As Double
DiscountRate = 0.25
ActiveCell = MsgBox("Discount Rate: " & _
Format(DiscountRate, "Percent"), _
vbOKOnly, "Exercise")
End Sub
Right-click the cell or group of cells whose format you want to change and click Format Cells...
Press Ctrl + 1 as a shortcut
Previous
http://www.functionx.com/vbaexcel/Lesson19.htm
Next
162
Introduction to Strings
A String
A string is one or a combination of characters. To declare a variable for it, you can use either
String or the Variant data types. To initialize the variable, put its value in double-quotes and
assign it to the variable. Here are examples:
Here is an example:
Sub Exercise()
ActiveCell = "AAA"
End Sub
When this code runs, the value AAA would be entered into any cell that is currently selected.
Sub Exercise()
Dim FirstName As Variant
Dim LastName As String
FirstName = "William"
LastName = "Sansen"
End Sub
String Concatenation
A string concatenation consists of adding one string to another. to support this operation, you can
use either the + or the & operator. Here are examples:
Sub Exercise()
Dim FirstName As Variant
Dim LastName As String
Dim FullName As String
FirstName = "William"
LastName = "Sansen"
FullName = LastName + ", " & FirstName
ActiveCell = "Full Name: " & FullName
End Sub
This would produce:
Introduction to Characters
Getting the ASCII Character of a Number
The characters used in the US English and the most common characters of Latin-based languages
are created in a list or map of character codes. Each character is represented with a small number
between 0 and 255. This means that each character must fit in a byte.
http://www.functionx.com/vbaexcel/Lesson20.htm
To help you find the equivalent ASCII character of such a number, the Visual Basic language
provides a function named Chr. Its syntax is:
Public Function Chr(ByVal CharCode As Integer) As String
When calling this function, pass a small number as argument. Here is an example:
Sub Exercise()
Dim Character As String
Dim Number As Integer
Number = 114
Character = Chr(Number)
ActiveCell = "The ASCII character of " & Number & " is " & Character
End Sub
This would produce:
Besides finding the ASCII equivalent of a number, the Chr() function can be used to apply some
behavior in a program. For example, a combination of Chr(13) and Chr(10) would break a line in
an expression, which is equivalent to the vbCrLf operator.
http://www.functionx.com/vbaexcel/Lesson20.htm
163
164
The Microsoft Excel library provides the LEN() function that produces the same result.
In Lesson 3, we saw that the Visual Basic language supports hexadecimal number and we saw how
to initialize an integer variable with a hexadecimal number. Now, on the other hand, if you have a
decimal number but need it in hexadecimal format, you can convert it. To support this operation,
you can call the Hex() function. Its syntax is:
Function Hex(ByVal Number As { Byte | Integer | Long | Variant} ) As String
This function is used to convert either an integer-based or a decimal number to its hexadecimal
equivalent. It returns the result as a string. Here is an example:
Sub Exercise()
Dim Number As Integer
Number = 28645
ActiveCell = Hex(Number)
End Sub
The Microsoft Excel library provides more functions to perform this type of operation.
Case Conversion
If you are presented with a string or an expression whose cases must be the same, you can
convert all of its characters in either uppercase or lowercase.
To convert a character, a string or an expression to uppercase, you can call the VBA's UCase() or
the Microsoft Excel's UPPER() functions. These functions take one argument as the string or
expression to be considered. The syntaxes are:
Function UCase(ByVal Value As String) As String
Function UPPER(ByVal Value As String) As String
Each function receives a character or string as argument. If a character is already in uppercase, it
would be returned the same. If the character is not a readable character, no conversion would
happen and the function would return it. If the character is in lowercase, it would be converted to
uppercase and the function would then return the uppercase equivalent.
Here is an example:
Sub Exercise()
Dim ProgrammingEnvironment As String
ProgrammingEnvironment = "Visual Basic for Application for Microsoft Excel"
ActiveCell = UCase(ProgrammingEnvironment)
End Sub
To convert a character or a string to lowercase, you can call the VBA's LCase() or the Microsoft
Excel's UPPER() functions. Their syntaxes are:
Function LCase(ByVal Value As String) As String
Function LOWER(ByVal Value As String) As String
The function takes a character or a string as argument. If a character is not a readable symbol, it
would be kept "as is". If the character is in lowercase, it would not be converted. If the character
is in uppercase, it would be converted to lowercase.
http://www.functionx.com/vbaexcel/Lesson20.htm
165
Finding a Sub-String
One of the most regular operations you will perform on a string consists of finding out whether it
contains a certain character or a certain contiguous group of characters. To help you with this
operation, the Visual Basic language provides the InStr() function and the Microsoft Excel library
equipped with the FIND() function. Their syntaxes are:
InStr([start, ]string1, string2[, compare])
FIND([Find_Text, Within_Text, Start_Num)
In the first version of the function, the String1 argument is the string on which the operation will
be performed. The String2 argument is the character or the sub-string to look for. If String2 is
found in String1 (as part of String1), the function return the position of the first character. Here is
an example:
The first version of the function asks the interpreter to check String1 from the left looking for
String2. If String1 contains more than one instance of String2, the function returns (only) the
position of the first instance. Any other subsequent instance would be ignored. If you want to skip
the first instance or want the interpreter to start checking from a position other than the left
character, use the second version. In this case, the Start argument allows you to specify the
starting position from where to start looking for String2 in String1.
The InStr() function is used to start checking a string from the left side. If you want to start
checking from the right side, call the InStrRev() function. Its syntax is:
InstrRev(stringcheck, stringmatch[, start[, compare]])
http://www.functionx.com/vbaexcel/Lesson20.htm
166
167
http://www.functionx.com/vbaexcel/Lesson20.htm
168
You can also create the message from other pieces of strings. The Prompt argument can be
made of up to 1024 characters. To display the Prompt on multiple lines, you can use either the
constant vbCrLf or the combination Chr(10) & Chr(13) between any two strings. Here is an
example:
Sub Exercise()
MsgBox ("Your logon credentials have been checked." & _
vbCrLf & "To complete your application, please " & _
"fill out the following survey")
End Sub
This would produce:
If you call the MsgBox() function with only the first argument, it is referred to as a method (a
method is a member function of a class; the class in this case is the Application on which you
are working). If you want to use the other arguments, you must treat MsgBox as a function.
That is, you must assign it to a variable or to an object.
Numeric Value
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
Display
When calling the MsgBox() function and specifying the button, you can use one of the above
constant numeric values. Here is an example that displays the Yes and the No buttons on the
message box:
Sub Exercise()
ActiveCell = MsgBox("Your logon credentials have been checked " & _
"and your application has been approved: " & _
"Congratulations!" & vbCrLf & _
"Before leaving, would you like " & _
"to take our survey survey now?", vbYesNo)
End Sub
This would produce:
Numeric Value
vbCritical
16
vbQuestion
32
vbExclamation
48
Description
http://www.functionx.com/vbaexcel/Lesson20.htm
vbInformation
169
64
To use one of these icons, you must combine the value of the button to the desired value of
the icon. To perform this combination, you use the OR operator. Here is an example:
Sub Exercise()
Dim iAnswer As Integer
iAnswer = MsgBox("Your logon credentials have been checked " & _
"and your application has been approved: Congratulations!" & _
vbCrLf & "Before leaving, would you like " & _
"to take our survey survey now?", vbYesNo Or vbQuestion)
End Sub
This would produce:
When calling the MsgBox() function, if you want to show one or more buttons and to show an
icon, you can use either two members of the MsgBoxStyle enumeration using the OR
operator, or you can add one of the constant values of the buttons to another contant values
for an icon. For example, 3 + 48 = 51 would result in displaying the buttons Yes, Ne, and
Cancel, and the exclamation icon.
Numeric
Value
vbDefaultButton1
vbDefaultButton2
256
vbDefaultButton3
512
Once again, to specify a default value, use the OR operator to combine a Default Button
Constant with any other combination. Here is an example:
Sub Exercise
ActiveCell = MsgBox("Your logon credentials have been checked " & _
"and your application has been approved: Congratulations!" & _
vbCrLf & "Before leaving, would you like " & _
"to take our survey survey now?", _
vbYesNo Or _
vbQuestion Or vbDefaultButton2)
End Sub
This would produce:
These additional buttons can be used to further control what the user can do:
Constant
vbApplicationModal
vbSystemModal
Value Effect
The user must dismiss the message box before proceeding with the
current database
The user must dismiss this message before using any other open
4096
application of the computer
0
http://www.functionx.com/vbaexcel/Lesson20.htm
Sub Exercise()
ActiveCell = MsgBox("Your logon credentials have been checked " & _
"and your application has been approved: Congratulations!" & _
vbCrLf & "Before leaving, would you like " & _
"to take our survey survey now?", _
vbYesNo Or vbQuestion, _
"Crofton Circle of Friends - Membership Application")
End Sub
This would produce:
Notice that the caption is now customized instead of the name of the application. The caption
can also be a string created from an expression or emanating from a variable or value.
Numeric Value
vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo
Upon reading the message on the input box, the user is asked to enter a piece of information.
The type of information the user is supposed to provide depends on you, the programmer.
Therefore, there are two important things you should always do. First you should let the user
know what type of information is requested. Is it a number (what type of number)? Is it a
string (such as the name of a country or a customer's name)? Is it the location of a file (such
as C:\Program Files\Homework)? Are you expecting a Yes/No True/False type of answer (if so,
how should the user provide it)? Is it a date (if it is a date, what format is the user supposed
to enter)? These questions mean that you should state a clear request to the user and specify
what kind of value you are expecting. A solution, also explicit enough, consists of providing an
http://www.functionx.com/vbaexcel/Lesson20.htm
170
171
Notice that the caption is now customized instead of the name of the application. The caption
can also be a string created from an expression or emanating from a variable or value.
Notice that, when the input box displays with a default value, the value is in the text box and
the value is selected. Therefore, if the value is fine, the user can accept it and click OK.
Another way you can use the default value is to provide a value the user can accept; that is,
the most common or most likely value the user would enter. Here is an example:
Sub Exercise()
ActiveCell = InputBox("Enter Birth State:", _
"Student Registration", "VA")
End Sub
Here is an example of running the program:
Once again, notice that the user can just accept the value and click OK or press Enter.
http://www.functionx.com/vbaexcel/Lesson20.htm
argument specifies the x coordinate of the input box; that is, the distance from its left border
to the left border of the monitor. The fifth argument specifies the distance from the top border
of the input box to the top border of the monitor.
172
Previous
http://www.functionx.com/vbaexcel/Lesson20.htm
Next
173
To initialize a Boolean variable, assign it a True or a False value. In the Visual Basic language, a
Boolean variable can also deal with numeric values. The False value is equivalent to 0. For
example, instead of False, you can initialize a Boolean variable with 0. Any other numeric value,
whether positive or negative, corresponds to True:
Sub Exercise()
Dim EmployeeIsMarried As Boolean
EmployeeIsMarried = -792730
Range("B2").FormulaR1C1 = "Employee Is Married? " & EmployeeIsMarried
End Sub
This would produce:
To pass an argument as a Boolean value, in the parentheses of the procedure, type the name of
the argument followed by the As Boolean expression. Here is an example:
Private Sub CheckingEmployee(ByVal IsFullTime As Boolean)
End Sub
In the same way, you can pass as many Boolean arguments as you need, and you can combine
Boolean and non-Boolean arguments as you judge necessary. Then, in the body of the procedure,
use (or do not use) the Boolean argument as you wish.
If the argument is holding any other value that cannot be identified as a number, the function
produces False. Here is an example:
Sub Exercise()
Dim Value As Variant
Value = #12/4/1770#
Range("B2").FormulaR1C1 = "Is Numeric? " & IsNumeric(Value)
End Sub
This would produce:
http://www.functionx.com/vbaexcel/Lesson21.htm
174
175
If the value of the argument cannot be evaluated to a valid date or time, the function returns
False. Here is an example:
Sub Exercise()
Dim DateHired As Variant
DateHired = "Who Knows?"
Range("B2").FormulaR1C1 = "Is it a valid date? " & IsDate(DateHired)
End Sub
This would produce:
Logical Operators
Introduction
A comparison is an operation used to get the boolean result of two values one checked against the
other. Such a comparison is performed between two values of the same type.
Equality
To compare two variables for equality, use the = operator. Its syntax is:
Value1 = Value2
The equality operation is used to find out whether two variables (or one variable and a constant)
hold the same value. From our syntax, the value of Value1 would be compared with the value of
Value2. If Value1 and Value2 hold the same value, the comparison produces a True result. If they
are different, the comparison renders false or 0.
http://www.functionx.com/vbaexcel/Lesson21.htm
176
Here is an example:
Sub Exercise()
Dim IsFullTime As Boolean
Range("B2").FormulaR1C1 = "Is Employee Full Time? " & IsFullTime)
IsFullTime = True
Range("B4").FormulaR1C1 = "Is Employee Full Time? " & IsFullTime)
End Sub
This would produce:
Inequality <>
As opposed to checking for equality, you may instead want to know whether two values are
different. The operator used to perform this comparison is <> and its formula is:
Variable1 <> Variable2
If the operands on both sides of the operator are the same, the comparison renders false. If both
operands hold different values, then the comparison produces a true result. This also shows that
the equality = and the inequality <> operators are opposite.
Here is an example:
Public Function IsDifferent(ByVal Value1 As Integer, _
ByVal Value2 As Integer) As Boolean
IsDifferent = Value1 <> Value2
End Function
Sub Exercise()
Dim a%, b%
Dim Result As Boolean
a% = 12: b% = 48
Result = IsDifferent(a%, b%)
Range("B2").FormulaR1C1 = "The resulting comparison of 12 <> 48 is " & Result
End Sub
This would produce:
To find out whether one value is lower than another, use the < operator. Its syntax is:
Value1 < Value2
The value held by Value1 is compared to that of Value2. As it would be done with other
operations, the comparison can be made between two variables, as in Variable1 < Variable2. If
the value held by Variable1 is lower than that of Variable2, the comparison produces a True.
Here is an example:
Sub Exercise()
Dim PartTimeSalary, ContractorSalary As Double
Dim IsLower As Boolean
PartTimeSalary = 20.15
ContractorSalary = 22.48
IsLower = PartTimeSalary < ContractorSalary
MsgBox ("Part Time Salary: " & PartTimeSalary & vbCrLf & _
"Contractor Salary: " & ContractorSalary & vbCrLf & _
"Is PartTimeSalary < ContractorSalary? " & IsLower)
PartTimeSalary = 25.55
ContractorSalary = 12.68
IsLower = PartTimeSalary < ContractorSalary
MsgBox ("Part Time Salary: " & PartTimeSalary & vbCrLf & _
"Contractor Salary: " & ContractorSalary & vbCrLf & _
"Is PartTimeSalary < ContractorSalary? " & IsLower)
End Sub
This would produce:
http://www.functionx.com/vbaexcel/Lesson21.htm
177
VBasic provides a logical operator that allows you to find out if one of two values is greater than
the other. The operator used for this operation uses the > symbol. Its syntax is:
Value1 > Value2
Both operands, in this case Value1 and Value2, can be variables or the left operand can be a
variable while the right operand is a constant. If the value on the left of the > operator is greater
than the value on the right side or a constant, the comparison produces a True value. Otherwise,
the comparison renders False or null:
Here is an example:
Sub Exercise()
Dim PartTimeSalary, ContractorSalary As Double
Dim IsLower As Boolean
PartTimeSalary = 20.15
ContractorSalary = 22.48
IsLower = PartTimeSalary > ContractorSalary
MsgBox ("Part Time Salary: " & PartTimeSalary & vbCrLf & _
"Contractor Salary: " & ContractorSalary & vbCrLf & _
"Is PartTimeSalary > ContractorSalary? " & IsLower)
PartTimeSalary = 25.55
ContractorSalary = 12.68
IsLower = PartTimeSalary > ContractorSalary
MsgBox ("Part Time Salary: " & PartTimeSalary & vbCrLf & _
"Contractor Salary: " & ContractorSalary & vbCrLf & _
"Is PartTimeSalary > ContractorSalary? " & IsLower)
End Sub
This would produce:
http://www.functionx.com/vbaexcel/Lesson21.htm
178
Operator
Previous
Meaning
Example
Opposite
<>
Equality to
a=b
<>
Not equal to
12 <> 7
<
Less than
25 < 84
>=
<=
>
>
Greater than
248 > 55
<=
>=
<
http://www.functionx.com/vbaexcel/Lesson21.htm
179
Next
180
Control
Name
Caption
First
Name:
Label
TextBox
txtFirstName
Last
Name:
Label
TextBox
txtLastName
Full
Name:
Label
TextBox
txtFullName
http://www.functionx.com/vbaexcel/Lesson22.htm
TaxRate = 33.0
MsgBox("Tax Rate: " & TaxRate & "%")
IsMarried = True
If IsMarried = True Then TaxRate = 30.65
MsgBox("Tax Rate: " & TaxRate & "%")
End Sub
This would produce:
If there are many statements to execute as a truthful result of the condition, you should write the
statements on alternate lines. Of course, you can use this technique even if the condition you are
examining is short. If you write the conditional statement in more than one line, you must end it
with End If on its own line. The formula used is:
If ConditionToCheck Then
Statement
End If
Here is an example:
Sub Exercise()
Dim IsMarried As Boolean
Dim TaxRate As Double
TaxRate = 33#
MsgBox ("Tax Rate: " & TaxRate & "%")
IsMarried = True
If IsMarried = True Then
TaxRate = 30.65
MsgBox ("Tax Rate: " & TaxRate & "%")
End If
End Sub
Sub txtFirstName_Change()
FirstName As String
LastName As String
FullName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
FullName = LastName & ", " & FirstName
txtFullName.Text = FullName
If LastName = "" Then txtFullName.Text = FirstName
End Sub
2. In the Variant combo box, select txtLastName and change its Change event as follows:
Private
Dim
Dim
Dim
Sub txtLastName_Change()
FirstName As String
LastName As String
FullName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
FullName = LastName & ", " & FirstName
txtFullName.Text = FullName
If LastName = "" Then txtFullName.Text = FirstName
End Sub
3. To test the form, on the main menu of Visual Basic, click Run -> Run Sub/UserForm
4. Click the top text box and type Julienne. Notice that only the first name displays in the Full
Name text box
http://www.functionx.com/vbaexcel/Lesson22.htm
181
182
5. Press Tab
6. In the other text box, start typing Pal and notice that the Full Name text box is changing
7. Complete it with Palace
8. Close the form and return to Microsoft Visual Basic
Based on this, if you want to check whether a newly declared and uninitialized Boolean variable is
false, you can omit the = False expression applied to it. Here is an example:
Sub Exercise()
Dim IsMarried As Boolean
Dim TaxRate As Double
TaxRate = 33#
If IsMarried Then TaxRate = 30.65
MsgBox ("Tax Rate: " & TaxRate & "%")
End Sub
This would produce:
Notice that there is no = after the If IsMarried expression. In this case, the value of the variable is
False. On the other hand, if you want to check whether the variable is True, make sure you
include the = True expression. Overall, whenever in doubt, it is safer to always initialize your
variable and it is safer to include the = True or = False expression when evaluating the variable:
Sub Exercise()
Dim IsMarried As Boolean
Dim TaxRate As Double
TaxRate = 36.45 ' %
IsMarried = True
If IsMarried = False Then TaxRate = 33.15
MsgBox ("Tax Rate: " & TaxRate & "%")
End Sub
In the previous lesson, we introduced some Boolean-based functions such as IsNumeric and
IsDate. The default value of these functions is True. This means that when you call them, you
can omit the = True expression.
183
The If...Then statement offers only one alternative: to act if the condition is true. Whenever you
would like to apply an alternate expression in case the condition is false, you can use the
If...Then...Else statement. The formula of this statement is:
If ConditionToCheck Then
Statement1
Else
Statement2
End If
When this section of code is executed, if the ConditionToCheck is true, then the first statement,
Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case
Statement2, is executed.
Here is an example:
Sub Exercise()
Dim MemberAge As Integer
Dim MemberCategory As String
MemberAge = 16
If MemberAge <= 18 Then
MemberCategory = "Teen"
Else
MemberCategory = "Adult"
End If
MsgBox ("Membership: " & MemberCategory)
End Sub
This would produce:
Sub txtFirstName_Change()
FirstName As String
LastName As String
FullName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
If LastName = "" Then
FullName = FirstName
Else
FullName = LastName & ", " & FirstName
End If
txtFullName.Text = FullName
End Sub
Private
Dim
Dim
Dim
Sub txtLastName_Change()
FirstName As String
LastName As String
FullName As String
FirstName = txtFirstName.Text
LastName = txtLastName.Text
If FirstName = "" Then
FullName = LastName
Else
FullName = LastName & ", " & FirstName
End If
txtFullName.Text = FullName
End Sub
2. Press F5 to test the form
3. After using the form, close it and return to Visual Basic
http://www.functionx.com/vbaexcel/Lesson22.htm
Immediate If
184
To assist you with checking a condition and its alternative, the Visual Basic language
provides a function named IIf. Its syntax is:
Public Function IIf( _
ByVal Expression As Boolean, _
ByVal TruePart As Variant, _
ByVal FalsePart As Variant _
) As Variant
This function operates like an If...Then...Else condition. It takes three required arguments
and returns a result of type Variant. This returned value will hold the result of the function.
The condition to check is passed as the first argument:
If that condition is true, the function returns the value of the TruePart argument and
the last argument is ignored
If the condition is false, the first argument is ignored and the function returns the value
of the second argument
As mentioned already, you can retrieved the value of the right argument and assign it to
the result of the function. The expression we saw early can be written as follows:
Sub Exercise()
Dim MemberAge As Integer
Dim MemberCategory As String
MemberAge = 16
MemberCategory = IIf(MemberAge <= 18, "Teen", "Adult")
MsgBox ("Membership: " & MemberCategory)
End Sub
This would produce the same result we saw earlier.
Sub CalucateOrder()
UnitPriceShirts As Double, UnitPricePants As Double
UnitPriceItem1 As Double, UnitPriceItem2 As Double
UnitPriceItem3 As Double, UnitPriceItem4 As Double
QuantityShirts As Integer, QuantityPants As Integer
QuantityItem1 As Integer, QuantityItem2 As Integer
http://www.functionx.com/vbaexcel/Lesson22.htm
Dim
Dim
Dim
Dim
Dim
Dim
QuantityShirts = IIf(IsNumeric(txtUnitPriceShirts), _
CInt(txtQuantityShirts), 0)
QuantityPants = IIf(IsNumeric(txtQuantityPants), _
CInt(txtQuantityPants), 0)
QuantityItem1 = IIf(IsNumeric(txtQuantityItem1), _
Int(txtQuantityItem1), 0)
QuantityItem2 = IIf(IsNumeric(txtQuantityItem2), _
CInt(txtQuantityItem2), 0)
QuantityItem3 = IIf(IsNumeric(txtQuantityItem3), _
CInt(txtQuantityItem3), 0)
QuantityItem4 = IIf(IsNumeric(txtQuantityItem4), _
CInt(txtQuantityItem4), 0)
TaxRate = IIf(IsNumeric(txtTaxRate), _
CDbl(txtTaxRate), 0)
SubTotalShirts = UnitPriceShirts
SubTotalPants = UnitPricePants *
SubTotalItem1 = UnitPriceItem1 *
SubTotalItem2 = UnitPriceItem2 *
SubTotalItem3 = UnitPriceItem3 *
SubTotalItem4 = UnitPriceItem4 *
* QuantityShirts
QuantityPants
QuantityItem1
QuantityItem2
QuantityItem3
QuantityItem4
txtSubTotalShirts = FormatNumber(SubTotalShirts)
txtSubTotalPants = FormatNumber(SubTotalPants)
txtSubTotalItem1 = FormatNumber(SubTotalItem1)
txtSubTotalItem2 = FormatNumber(SubTotalItem2)
txtSubTotalItem3 = FormatNumber(SubTotalItem3)
txtSubTotalItem4 = FormatNumber(SubTotalItem4)
CleaningTotal = SubTotalShirts + SubTotalPants + _
SubTotalItem1 + SubTotalItem2 + _
SubTotalItem3 + SubTotalItem4
TaxAmount = CleaningTotal * TaxRate / 100
OrderTotal = CleaningTotal + TaxAmount
txtCleaningTotal = FormatNumber(CleaningTotal)
txtTaxAmount = FormatNumber(TaxAmount)
txtOrderTotal = FormatNumber(OrderTotal)
End Sub
Private Sub txtUnitPriceShirts_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtQuantityShirts_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtUnitPricePants_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
http://www.functionx.com/vbaexcel/Lesson22.htm
185
186
End Sub
Private Sub txtQuantityPants_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtUnitPriceItem1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtQuantityItem1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtUnitPriceItem2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtQuantityItem2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtUnitPriceItem3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtQuantityItem3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtUnitPriceItem4_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtQuantityItem4_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
Private Sub txtTaxRate_Exit(ByVal Cancel As MSForms.ReturnBoolean)
CalucateOrder
End Sub
5. Close Microsoft Visual Basic
6. Save the workbook
Choosing a Value
We have learned how to check whether a condition is True or False and take an action. Here
is an example:
Sub Exercise()
Dim Status As Integer, EmploymentStatus As String
Status = 1
EmploymentStatus = "Unknown"
If Status = 1 Then
EmploymentStatus = "Full Time"
End If
MsgBox ("Employment Status: " & EmploymentStatus)
End Sub
To provide an alternative to this operation, the Visual Basic language provides a function
named Choose. Its syntax is:
Public Function Choose( _
ByVal Index As Double, _
ByVal ParamArray Choice() As Variant _
) As Variant
This function takes two required arguments. The fist argument is equivalent to the
ConditionToCheck of our If...Then formula. For the Choose() function, this first argument
must be a number. This is the value against which the second argument will be compared.
Before calling the function, you must know the value of the first argument. To take care of
this, you can first declare a variable and initialize it with the desired value. Here is an
example:
Sub Exercise()
Dim Status As Byte, EmploymentStatus As String
Status = 1
EmploymentStatus = Choose(Status, ...)
MsgBox ("Employment Status: " & EmploymentStatus)
End Sub
The second argument can be the Statement of our formula. Here is an example:
http://www.functionx.com/vbaexcel/Lesson22.htm
187
We will see in the next sections that the second argument is actually a list of values and
each value has a specific position referred to as its index. To use the function in an
If...Then scenario, you pass only one value as the second argument. This value/argument
has an index of 1. When the Choose() function is called in an If...Then implementation, if
the first argument holds a value of 1, the second argument is validated.
When the Choose() function has been called, it returns a value of type Variant. You can
retrieve that value, store it in a variable and use it as you see fit. Here is an example:
Sub Exercise()
Dim Status As Byte, EmploymentStatus As String
Status = 1
EmploymentStatus = Choose(Status, "Full Time")
MsgBox ("Employment Status: " & EmploymentStatus)
End Sub
This would produce:
In some cases, the Choose() function can produce a null result. Consider the same program
we used earlier but with a different value:
Module Exercise
Sub Exercise
Dim Status As Integer, EmploymentStatus As String
Status = 2
EmploymentStatus = Choose(Status, "Full Time")
MsgBox(EmploymentStatus)
Return 0
End Function
End Module
This would produce an error because there is no value in index 2 after the Status variable
has been initialized with 2. To use this function as an alternative to the If...Then...Else
operation, you can pass two values for the second argument. The second argument is
actually passed as a list of values. Each value has a specific position as its index. To use the
function in an If...Then...Else implementation, pass two values for the second argument.
Here is an example:
Choose(Status, "Full Time", "Part Time")
The second argument to the function, which is the first value of the Choose argument, has
an index of 1. The third argument to the function, which is the second value of the Choose
argument, has an index of 2.
When the Choose() function is called, if the first argument has a value of 1, then the
second argument is validated. If the first argument has a value of 2, then the third
argument is validated. As mentioned already, you can retrieve the returned value of the
function and use it however you want. Here is an example:
Sub Exercise()
Dim Status As Integer, EmploymentStatus As String
Status = 2
EmploymentStatus = Choose(Status, "Full Time", "Part Time")
MsgBox ("Employment Status: " & EmploymentStatus)
End Sub
This would produce:
Switching to a Value
As another alternative to an If...Then condition, the Visual Basic language provides a
function named Switch. Its syntax is:
http://www.functionx.com/vbaexcel/Lesson22.htm
http://www.functionx.com/vbaexcel/Lesson22.htm
188
189
Previous
http://www.functionx.com/vbaexcel/Lesson22.htm
Next
190
Control
Name
Label
Caption/Text
TextAlign: 3 frmTextAlignRight
TextBox
txtQuantity
CommandButton
cmdEvaluate
Evaluate
Frame
Label
TextBox
Label
Other Properties
Number of CDs:
txtUnitPrice
0.00
TextAlign: 3 frmTextAlignRight
http://www.functionx.com/vbaexcel/Lesson23.htm
TextBox
txtTotalPrice
0.00
TextAlign: 3 frmTextAlignRight
Sub cmdEvaluate_Click()
Quantity As Integer
UnitPrice As Currency
TotalPrice As Currency
Quantity = CInt(txtQuantity.Text)
' The price of one CD will depend on the number ordered
' The more the customer orders, the lower value each
If Quantity < 20 Then
UnitPrice = 20
ElseIf Quantity < 50 Then
UnitPrice = 15
ElseIf Quantity < 100 Then
UnitPrice = 12
ElseIf Quantity < 500 Then
UnitPrice = 8
Else
UnitPrice = 5
End If
TotalPrice = Quantity * UnitPrice
txtUnitPrice.Text = CStr(UnitPrice)
txtTotalPrice.Text = CStr(TotalPrice)
End Sub
2. Press F5 to test the form
3. Perform the calculations with different quantities. For example, in the top text box, type 1250
and click Evaluate
http://www.functionx.com/vbaexcel/Lesson23.htm
191
192
Conditional Returns
A function is meant to return a value. Sometimes, it will perform some tasks whose results would
lead to different results. A function can return only one value (we saw that, by passing arguments
by reference, you can make a procedure return more than one value) but you can make it render
a result depending on a particular behavior. If a function is requesting an answer from the user,
since the user can provide different answers, you can treat each result differently. Consider the
following function:
Private Function SetMembershipLevel$()
Dim MemberAge%
MemberAge% = InputBox("Enter the Member's Age")
If MemberAge% < 18 Then
SetMembershipLevel$ = "Teen"
ElseIf MemberAge% < 55 Then
SetMembershipLevel$ = "Adult"
End If
End Function
Sub Exercise()
Dim Membership$
MsgBox ("Membership: " & Membership$)
http://www.functionx.com/vbaexcel/Lesson23.htm
End Sub
193
At first glance, this function looks fine. The user is asked to provide a number. If the user enters a
number less than 18 (excluded), the function returns Teen. Here is an example of running the
program:
If the user provides a number between 18 (included) and 55, the function returns the Adult. Here
is another example of running the program:
What if there is an answer that does not fit those we are expecting? The values that we have
returned in the function conform only to the conditional statements and not to the function.
Remember that in If Condidion Statement, the Statement executes only if the Condition is true.
Here is what will happen. If the user enters a number higher than 55 (excluded), the function will
not execute any of the returned statements. This means that the execution will reach the End
Function line without encountering a return value. This also indicates to the compiler that you
wrote a function that is supposed to return a value, but by the end of the method, it didn't return
a value. Here is another example of running the program:
To solve this problem, you have various alternatives. If the function uses an If...Then condition,
you can create an Else section that embraces any value other than those validated previously.
Here is an example:
Private Function SetMembershipLevel$()
Dim MemberAge%
MemberAge% = InputBox("Enter the Member's Age")
If MemberAge% < 18 Then
SetMembershipLevel$ = "Teen"
ElseIf MemberAge% < 55 Then
SetMembershipLevel$ = "Adult"
Else
SetMembershipLevel$ = "Senior"
End If
End Function
Sub Exercise()
Dim Membership$
Membership$ = SetMembershipLevel$()
MsgBox ("Membership: " & Membership$)
End Sub
http://www.functionx.com/vbaexcel/Lesson23.htm
This time, the Else condition would execute if no value applies to the If or ElseIf conditions and
the compiler would not produce a warning. Here is another example of running the program:
An alternative is to provide a last return value just before the End Function line. In this case, if
the execution reaches the end of the function, it would still return something but you would know
what it returns. This would be done as follows:
Private Function SetMembershipLevel$()
Dim MemberAge%
MemberAge% = InputBox("Enter the Member's Age")
If MemberAge% < 18 Then
SetMembershipLevel$ = "Teen"
ElseIf MemberAge% < 55 Then
SetMembershipLevel$ = "Adult"
End If
SetMembershipLevel$ = "Senior"
End Function
If the function uses an If condition, both implementations would produce the same result.
5. Click OK
6. On the Ribbon, click Stop Recording
http://www.functionx.com/vbaexcel/Lesson23.htm
194
195
End If
GetEmployeeName = Name
End Function
Public Sub LocateEmployee()
'
' Macro Name: LocateEmployee
' This macro is used to find the name of an employee
' based on the employee number
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim EmployeeNumber As Long, EmployeeName As String
If IsEmpty(Range("C4")) Then
MsgBox "You must enter the employee number in cell C4"
Range("D4").FormulaR1C1 = ""
EmployeeNumber = 0
Else
EmployeeNumber = CLng(Range("C4"))
End If
EmployeeName = GetEmployeeName(EmployeeNumber)
Range("D4").FormulaR1C1 = EmployeeName
End Sub
10. Return to Microsoft Excel
11. In cell C4, type 54080 and press Enter
12. Press Ctrl + Shift + E to see the result
http://www.functionx.com/vbaexcel/Lesson23.htm
So far, we have used only strings for the values of the second argument of the Choose() function.
In reality, the values of the second argument can be almost anything. One value can be a
constant. Another value can be a string. Yet another value can come from calling a function. Here
is an example:
Private Function ShowContractors$()
ShowContractors$ = "=-= List of Contractors =-=" & vbCrLf & _
"Martin Samson" & vbCrLf & _
"Genevive Lam" & vbCrLf & _
"Frank Viel" & vbCrLf & _
"Henry Rickson" & vbCrLf & _
"Samuel Lott"
End Function
Sub Exercise()
Dim Status As Byte, Result$
Status = 3
Result = Choose(Status, _
"Employment Status: Full Time", _
"Employment Status: Part Time", _
ShowContractors, _
"Seasonal Employment")
MsgBox (Result)
End Sub
This would produce:
http://www.functionx.com/vbaexcel/Lesson23.htm
196
197
ConditionXToCheck, StatementX
As the function is accessed, the compiler checks each condition. If a condition X is true, its
statement is executed. If a condition Y is false, the compiler skips it. You can provide as many of
these combinations as you want. Here is an example:
Private Enum EmploymentStatus
FullTime
PartTime
Contractor
Seasonal
End Enum
Sub Exercise()
Dim Status As EmploymentStatus
Dim Result As String
Status = EmploymentStatus.Contractor
Result = "Unknown"
Result = Switch(Status
Status
Status
Status
=
=
=
=
In a true If...Then...ElseIf...ElseIf condition, we saw that there is a possibility that none of the
conditions would fit, in which case you can add a last Else statement. The Switch() function also
supports this situation if you are using a number, a character, or a string. To provide this last
alternative, instead of a ConditionXToCheck expressionk, enter True, and include the necessary
statement. Here is an example:
Sub Exercise()
Dim Status As Byte
Dim Result As String
Status = 12
Result = Switch(Status = 1, "Full Time", _
Status = 2, "Part Time", _
Status = 3, "Contractor", _
Status = 4, "Seasonal", _
True, "Unknown")
MsgBox ("Employment Status: " & Result)
End Sub
This would produce:
Remember that you can also use True with a character. Here is an example:
Sub Exercise()
Dim Gender As String
Dim Result As String
Gender = "H"
Result = Switch(Gender = "f", "Female", _
Gender = "F", "Female", _
Gender = "m", "Male", _
Gender = "M", "Male", _
True, "Unknown")
MsgBox ("Gender: " & Result)
End Sub
This would produce:
198
Previous
http://www.functionx.com/vbaexcel/Lesson23.htm
Next
199
http://www.functionx.com/vbaexcel/Lesson24.htm
200
http://www.functionx.com/vbaexcel/Lesson24.htm
7. To open Microsoft Visual Basic, on the Ribbon, click Developer and, in the Code section, click
Visual Basic:
8. Right-click the Time Left text box (the text box on the right side of Time Left) and click View
Code
9. In the Objects combo box, make sure txtTimeLeft is selected.
In the Procedure combo box, select Exit and implement the event as follows:
http://www.functionx.com/vbaexcel/Lesson24.htm
201
Combining Cases
As mentioned in our introduction, the Select Case can use a value other than an integer. For
example you can use a character:
Sub Exercise
Dim Gender As String
Gender = "M"
Select Case Gender
Case "F"
http://www.functionx.com/vbaexcel/Lesson24.htm
202
MsgBox("Female")
Case "M"
MsgBox("Male")
Case Else
MsgBox("Unknown")
End Select
203
Return 0
End Function
End Sub
This would produce:
Notice that in this case we are using only upper case characters. If want to validate lower case
characters also, we may have to create additional case sections for each. Here is an example:
Sub Exercise
Dim Gender As String
Gender = "f"
Select Case Gender
Case "f"
MsgBox("Female")
Case "F"
MsgBox("Female")
Case "m"
MsgBox("Male")
Case "M"
MsgBox("Male")
Case Else
MsgBox("Unknown")
End Select
End Sub
This would produce:
Instead of using one value for a case, you can apply more than one. To do this, on the right side
of the Case keyword, you can separate the expressions with commas. Here are examples:
Sub Exercise
Dim Gender As String
Gender = "F"
Select Case Gender
Case "f", "F"
MsgBox("Female")
Case "m", "M"
MsgBox("Male")
Case Else
MsgBox("Unknown")
End Select
End Sub
http://www.functionx.com/vbaexcel/Lesson24.htm
204
We also saw that the Visual Basic language provides the Choose() function that can check a
condition and take an action. The Choose() function is another alternative to a Select...Case
http://www.functionx.com/vbaexcel/Lesson24.htm
http://www.functionx.com/vbaexcel/Lesson24.htm
205
http://www.functionx.com/vbaexcel/Lesson24.htm
206
Sub Exercise
Dim Answer As Byte
207
Answer = InputBox(" -=- Multiple Choice Question -=-" & vbCrLf & _
"To create a constant in your code, " & _
"you can use the Constant keyword" & vbCrLf & _
"Your choice (1=True/2=False)? ")
Leaving:
End Sub
Here is an example of executing the program with Answer = 1:
http://www.functionx.com/vbaexcel/Lesson24.htm
208
In this case, the Not operator is used to change the logical value of the variable. When a
Boolean variable has been "notted", its logical value has changed. If the logical value was
True, it would be changed to False and vice versa. Therefore, you can inverse the logical
value of a Boolean variable by "notting" or not "notting" it.
Now consider the following program we saw in Lesson 11:
Sub Exercise
Dim IsMarried As Boolean
Dim TaxRate As Double
TaxRate = 33.0
MsgBox("Tax Rate: " & TaxRate & "%")
IsMarried = True
If IsMarried = True Then
TaxRate = 30.65
MsgBox("Tax Rate: " & TaxRate & "%")
End If
End Sub
This would produce:
Probably the most classic way of using the Not operator consists of reversing a logical
expression. To do this, you precede the logical expression with the Not operator. Here is an
example:
Sub Exercise
Dim IsMarried As Boolean
Dim TaxRate As Double
TaxRate = 33.0
MsgBox("Tax Rate: " & TaxRate & "%")
IsMarried = True
If Not IsMarried Then
TaxRate = 30.65
MsgBox("Tax Rate: " & TaxRate & "%")
End If
End Sub
This would produce:
http://www.functionx.com/vbaexcel/Lesson24.htm
Loop Repeaters
Introduction
A loop is a technique used to repeat an action. The Visual Basic language presents many
variations of loops. They combine the Do and the Loop keywords.
This interpreter first executes the Statement or Statements. After executing the
Statement(s) section, the interpreter checks the Condition. If the Condition is true, then the
interpreter returns to the Statement(s) and execute(s) it(them). The interpreter keeps
doing this check-execution gymnastic. As long as the Condition is true, the Statement(s)
section will be executed and the Condition will be tested again. If the Condition is false or
once the condition becomes false, the statement will not be executed and the program will
move on. Here is an example:
Sub Exercise
Dim Answer As String
Do
Answer = InputBox("Are we there yet (1=Yes/0=No)? ")
Loop While Answer <> "1"
MsgBox("Wonderful, we have arrived")
End Sub
Here is an example of running the program:
http://www.functionx.com/vbaexcel/Lesson24.htm
209
210
As you may guess already, the Condition must provide a way for it to be true or to be false.
Otherwise, the looping would be executed continually.
http://www.functionx.com/vbaexcel/Lesson24.htm
http://www.functionx.com/vbaexcel/Lesson24.htm
211
Here is an example:
212
Sub Exercise
Dim Answer As String
Answer = "0"
Do Until Answer = "1"
Answer = InputBox("Are we there yet (1=Yes/0=No)? ")
Loop
MsgBox("Wonderful, we have arrived")
End Sub
Loop Counters
Introduction
The looping statements we reviewed above are used when you do not know or cannot
anticipate the number of times a condition needs to be checked in order to execute a
statement. If you know with certainty how many times you want to execute a statement,
you can use another form of loops that use the For...Next expression.
Private
Dim
Dim
Dim
Dim
http://www.functionx.com/vbaexcel/Lesson24.htm
In some cases, you may want to exit a conditional statement or a loop before its end. To
assist with with this, the Visual Basic language provides the Exit keyword. This keyword
works like an operator. It can be applied to a procedure or a For loop. Consider the
following procedure:
Sub Exercise()
MsgBox("Patricia Katts")
MsgBox("Gertrude Monay")
MsgBox("Hermine Nkolo")
MsgBox("Paul Bertrand Yamaguchi")
End Sub
http://www.functionx.com/vbaexcel/Lesson24.htm
213
When the procedure is called, it displays four message boxes that each shows a name.
Imagine that at some point you want to ask the interpreter to stop in the middle of a
procedure. To do this, in the section where you want to stop the flow of a procedure, type
Exit Sub. Here is an example:
Sub Exercise()
MsgBox("Patricia Katts")
MsgBox("Gertrude Monay")
Exit Sub
MsgBox("Hermine Nkolo")
MsgBox("Paul Bertrand Yamaguchi")
End Sub
This time, when the program runs, the procedure would be accessed and would start
displaying the message boxes. After displaying two, the Exit Sub would ask the interpreter
to stop and get out of the procedure.
Because a function is just a type of procedure that is meant to return a value, you can use
the Exit keyword to get out of a function before the End Function line. To do this, in the
section where you want to stop the flow of the function, type Exit Function.
Change the code of the FindEmployee macro as follows:
Sub FindEmployeee()
'
' FindEmployeee Macro
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim EmployeeNumber As Long, EmployeeName As String
If IsEmpty(Range("C4")) Then
MsgBox "You must enter the employee number in cell C4"
Range("D4").FormulaR1C1 = ""
Exit Sub
Else
EmployeeNumber = CLng(Range("C4"))
End If
If EmployeeNumber = 22804 Then
Range("D4").FormulaR1C1 = "Helene Mukoko"
ElseIf EmployeeNumber = 92746 Then
Range("D4").FormulaR1C1 = "Raymond Kouma"
ElseIf EmployeeNumber = 54080 Then
Range("D4").FormulaR1C1 = "Henry Larson"
ElseIf EmployeeNumber = 86285 Then
Range("D4").FormulaR1C1 = "Gertrude Monay"
Else
Range("D4").FormulaR1C1 = "Unknown"
End
Exiting a Do Loop
You can also use the Exit operator to get out of a Do loop. To do this, inside of a Do loop
where you want to stop, type Exit Do.
http://www.functionx.com/vbaexcel/Lesson24.htm
214
215
"")
"")
"")
"")
Previous
http://www.functionx.com/vbaexcel/Lesson24.htm
Next
216
Logical Conjunction
Introduction
As mentioned already, you can nest one conditional statement inside of another. To illustrate,
imagine you create a workbook that would be used by a real estate company that sells houses.
You may face a customer who wants to purchase a single family house but the house should not
cost more than $550,001. To implement this scenario, you can first write a procedure that asks
the user to specify a type of house and then a conditional statement would check it. Here is an
example:
Sub Exercise
Dim TypeOfHouse As String
Dim Choice As Integer
Dim Value As Double
TypeOfHouse = "Unknown"
Choice = CInt(InputBox("Enter the type of
& vbCrLf & _
"1. Single Family" & vbCrLf
"2. Townhouse" & vbCrLf & _
"3. Condominium" & vbCrLf &
"You Choice? "))
Value = CDbl(InputBox("Up to how much can
http://www.functionx.com/vbaexcel/Lesson25.htm
217
In that section, you can then write code that would request and check the value the user entered.
If that value is valid, you can take necessary action. Here is an example:
Sub Exercise
Dim TypeOfHouse As String
Dim Choice As Integer
Dim Value As Double
TypeOfHouse = "Unknown"
Choice = CInt(InputBox("Enter the type of
& vbCrLf & _
"1. Single Family" & vbCrLf
"2. Townhouse" & vbCrLf & _
"3. Condominium" & vbCrLf &
"You Choice? "))
Value = CDbl(InputBox("Up to how much can
A Conditional Conjunction
Using conditional nesting, we have seen how you can write one conditional statement that
depends on another. But you must write one first condition, check it, then nest the other
condition. This works fine and there is nothing against it.
To provide you with an alternative, you can use what is referred to as a logical conjunction. It
consists of writing one If...Then expression that checks two conditions at the same time. To
illustrate, once again consider a customer who wants to purchase a single family home that is less
than $550,000. You can consider two statements as follows:
a. The house is single family
b. The house costs less than $550,000
To implement it, you would need to write an If...Then condition as:
If The house is single family AND The house costs less than $550,000 Then
Validate
End If
In the Visual Basic language, the operator used to perform a logical conjunction is And. Here is an
example of using it:
Sub Exercise
Dim TypeOfHouse As String
Dim Choice As Integer
Dim Value As Double
TypeOfHouse = "Unknown"
Choice = _
CInt(InputBox("Enter the type of house you want to purchase" & vbCrLf & _
"1. Single Family" & vbCrLf & _
"2. Townhouse" & vbCrLf & _
"3. Condominium" & vbCrLf & vbCrLf & _
"You Choice? "))
Value = CDbl(InputBox("Up to how much can you afford?"))
TypeOfHouse = Choose(Choice, "Single Family", _
http://www.functionx.com/vbaexcel/Lesson25.htm
"Townhouse", _
"Condominium")
218
By definition, a logical conjunction combines two conditions. To make the program easier to read,
each side of the conditions can be included in parentheses. Here is an example:
Sub Exercise
. . . No Change
If (TypeOfHouse = "Single Family") And (Value <= 550000) Then
MsgBox("Desired House Type:
" & vbTab & TypeOfHouse & vbCrLf & _
"Maximum value afforded: " & vbTab & FormatCurrency(Value))
MsgBox("Desired House Matched")
Else
MsgBox("The House Doesn't Match the Desired Criteria")
End If
End Sub
To understand how logical conjunction works, from a list of real estate properties, after selecting
the house type, if you find a house that is a single family home, you put it in the list of considered
properties:
Type of House
House
True
If you find a house that is less than or equal to $550,000, you retain it:
Price Range
Value
$550,000
True
For the current customer, you want a house to meet BOTH criteria. If the house is a town house,
based on the request of our customer, its conditional value is false. If the house is less than
$550,000, such as $485,000, the value of the Boolean Value is true:
http://www.functionx.com/vbaexcel/Lesson25.htm
219
If the house is a town house, based on the request of our customer, its conditional value is false.
If the house is more than $550,000, the value of the Boolean Value is true. In logical conjunction,
if one of the conditions is false, the result if false also. This can be illustrated as follows:
Type of House
House Value
Result
Town House
$625,000
False
False
False
Suppose we find a single family home. The first condition is true for our customer. With the AND
Boolean operator, if the first condition is true, then we consider the second criterion. Suppose that
the house we are considering costs $750,500: the price is out of the customer's range. Therefore,
the second condition is false. In the AND Boolean algebra, if the second condition is false, even if
the first is true, the whole condition is false. This would produce the following table:
Type of House
House Value
Result
Single Family
$750,500
True
False
False
Suppose we find a townhouse that costs $420,000. Although the second condition is true, the first
is false. In Boolean algebra, an AND operation is false if either condition is false:
Type of House
House Value
Result
Town House
$420,000
False
True
False
If we find a single family home that costs $345,000, both conditions are true. In Boolean algebra,
an AND operation is true if BOTH conditions are true. This can be illustrated as follows:
Type of House
House Value
Result
Single Family
$345,000
True
True
True
If Condition2 is
Condition1
AND
Condition2
False
False
False
False
True
False
True
False
False
True
True
True
As you can see, a logical conjunction is true only of BOTH conditions are true.
Combining Conjunctions
As seen above, the logical conjunction operator is used to combine two conditions. In some cases,
you will need to combine more than two conditions. Imagine a customer wants to purchase a
single family house that costs up to $450,000 with an indoor garage. This means that the house
must fulfill these three requirements:
A. The house is a single family home
B. The house costs less than $450,001
C. The house has an indoor garage
Here is the program that could be used to check these conditions:
Sub Exercise
Dim TypeOfHouse As String
Dim Choice As Integer
Dim Value As Double
Dim IndoorGarageAnswer As Integer
Dim Answer As String
TypeOfHouse = "Unknown"
Choice = _
CInt(InputBox("Enter the type of house you want to purchase" _
& vbCrLf & _
"1. Single Family" & vbCrLf & _
http://www.functionx.com/vbaexcel/Lesson25.htm
220
Criteria")
We saw that when two conditions are combined, the interpreter first checks the first condition,
followed by the second. In the same way, if three conditions need to be considered, the
interpreter evaluates the truthfulness of the first condition:
Type of House
A
Town House
False
If the first condition (or any condition) is false, the whole condition is false, regardless of the
outcome of the other(s). If the first condition is true, then the second condition is evaluated for its
truthfulness:
Type of House
Property Value
Single Family
$655,000
True
False
A AND B
True
False
False
When evaluating three conditions, if either the first or the second is false, since the whole
condition would become false, there is no reason to evaluate the third. If both the first and the
second conditions are false, there is also no reason to evaluate the third condition. Only if the first
two conditions are true will the third condition be evaluated whether it is true:
Type of House
Property Value
Indoor Garage
C
Single Family
$425,650
None
True
True
False
The combination of these conditions in a logical conjunction can be written as A AND B AND C. If
the third condition is false, the whole combination is considered false:
A
A AND B
A AND B AND
C
True
True
True
False
False
From our discussion so far, the truth table of the combinations can be illustrated as follows:
C
A AND B AND
C
False
Don't Care
Don't Care
False
True
False
Don't Care
False
True
True
False
False
The whole combination is true only if all three conditions are true. This can be illustrated as
follows:
A
A AND B AND
C
False
False
False
False
False
False
True
False
True
False
False
False
True
False
True
False
http://www.functionx.com/vbaexcel/Lesson25.htm
False
True
False
False
False
True
True
False
True
True
False
False
True
True
True
True
Logical Disjunction: OR
Introduction
Our real estate company has single family homes, townhouses, and condominiums. All of the
condos have only one level, also referred to as a story. Some of the single family homes have
one story, some have two and some others have three levels. All townhouses have three levels.
Another customer wants to buy a home. The customer says that he primarily wants a condo,
but if our real estate company doesn't have a condominium, that is, if the company has only
houses, whatever it is, whether a house or a condo, it must have only one level (story) (due to
an illness, the customer would not climb the stairs). When considering the properties of our
company, we would proceed with these statements:
a. The property is a condominium
b. The property has one story
If we find a condo, since all of our condos have only one level, the criterion set by the customer
is true. Even if we were considering another (type of) property, it wouldn't matter. This can be
resumed in the following table:
Type of House
House
Condominium
True
The other properties would not be considered, especially if they have more than one story:
Number of Stories
Value
False
One Story
Condominium or 1 Story
True
False
True
http://www.functionx.com/vbaexcel/Lesson25.htm
221
222
As done for the And operator, to make a logical disjunction easy to read, you can include each
statement in parentheses:
Sub Exercise
. . . No Change
If (Choice = 1) Or (Stories = 1) Then
MsgBox ("Desired House Type:" & vbTab & TypeOfHouse & vbCrLf & _
"Number of Stories:" & vbTab & vbTab & Stories)
MsgBox ("Desired House Matched")
Else
MsgBox ("The House Doesn't Match the Desired Criteria")
End If
End Sub
Suppose that, among the properties our real estate company has available, there is no
condominium. In this case, we would then consider the other properties:
Type of House
House
Single Family
False
If we have a few single family homes, we would look for one that has only one story. Once we
find one, our second criterion becomes true:
Type of House
One Story
Condominium OR 1 Story
False
True
True
If we find a condo and it is one story, both criteria are true. This can be illustrated in the
http://www.functionx.com/vbaexcel/Lesson25.htm
following table:
223
Type of House
One Story
False
True
Condominium OR 1 Story
True
True
True
True
A Boolean OR operation produces a false result only if BOTH conditions ARE FALSE:
If Condition1 is
If Condition2 is
False
True
Condition1 OR Condition2
True
True
False
True
True
True
True
False
False
False
Combinations of Disjunctions
As opposed to evaluating only two conditions, you may face a situation that presents three of
them and must consider a combination of more than two conditions. You would apply the same
logical approach we reviewed for the logical conjunction, except that, in a group of logical
disjunctions, if one of them is true, the whole statement becomes true.
http://www.functionx.com/vbaexcel/Lesson25.htm
224
Handling Errors
Introduction to Errors
A computer application is supposed to run as smooth as possible. Unfortunately, this is not
always the case. A form may close unexpectedly. A control on a form may hide itself at the
wrong time. The application may crash. A calculation may produce unexpected results, etc.
You can predict some of these effects and take appropriate actions. Some other problems are not
under your control. Fortunately, both Microsoft Excel and the VBA language provide various tools
or means of dealing with errors.
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
In Case of Error
Jump to a Label
We saw that you can create a label that would present a message to the user when an error
occurs. Before an error occurs, you would indicate to the compiler where to go if an error occurs.
To provide this information, under the line that starts the procedure, type an On Error GoTo
expression followed by the name of the label where you created the message. Here is an example:
Private Sub cmdCalculate_Click()
On Error GoTo ThereWasBadCalculation
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(txtHourlySalary)
WeeklyTime = CDbl(txtWeeklyTime)
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
txtWeeklySalary = FormatNumber(WeeklySalary)
Exit Sub
ThereWasBadCalculation:
MsgBox "There was a problem when performing the calculation"
End Sub
The On Error GoTo indicates to the compiler where to transfer code if an error occurs.
Go to a Numbered Label
Instead of defining a lettered label where to jump in case of error, you can create a numeric label:
Private Sub cmdCalculate_Click()
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
HourlySalary = CDbl(txtHourlySalary)
WeeklyTime = CDbl(txtWeeklyTime)
WeeklySalary = HourlySalary * WeeklyTime
txtWeeklySalary = FormatNumber(WeeklySalary)
Exit Sub
28:
MsgBox "There was a problem when performing the calculation"
End Sub
After creating the numeric label, you can ask the compiler to jump to it if a problem occurs. To do
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
225
this, type On Error GoTo followed by the numeric label. The compiler would still jump to it when
appropriate. Here is an example:
Private Sub cmdCalculate_Click()
On Error GoTo 28
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
HourlySalary = CDbl(txtHourlySalary)
WeeklyTime = CDbl(txtWeeklyTime)
WeeklySalary = HourlySalary * WeeklyTime
txtWeeklySalary = FormatNumber(WeeklySalary)
Exit Sub
28:
MsgBox "There was a problem when performing the calculation"
End Sub
Notice that the numeric label works like the lettered label. In other words, before writing the On
Error GoTo expression, you must have created the label. In reality, this is not a rule. You can ask
the compiler to let you deal with the error one way or another. To do this, use the On Error
GoTo 0 (or On Error GoTo -1) expression. Here is an example:
Private Sub cmdCalculate_Click()
On Error GoTo 0
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
HourlySalary = CDbl(txtHourlySalary)
WeeklyTime = CDbl(txtWeeklyTime)
WeeklySalary = HourlySalary * WeeklyTime
txtWeeklySalary = FormatNumber(WeeklySalary)
End Sub
In this case, if/when the error occurs, you must have a way to deal with it.
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
226
txtWeeklySalary = FormatNumber(WeeklySalary)
Exit Sub
ThereWasBadCalculation:
MsgBox "There was a problem when performing the calculation"
Resume Next
End Sub
We know that in our code, there was probably a problem, which is the reason we presented a
message to the user. Then, when code resumes, where should the compiler go? After all, the
problem was not solved. One way you can deal with the problem is to provide an alternative to
what caused the problem, since you are supposed to know what type of problem occurred (in the
next sections, we will analyze the types of problems that can occur). In the case of an arithmetic
calculation, imagine we know that the problem was caused by the user typing an invalid number
(such as typing a name where a number was expected). Instead of letting the program crash, we
can provide a number as an alternative. The easiest number is 0.
Before asking the compiler to resume, to provide an alternative solution (a number in this case),
you can re-initialize the variable that caused the error. Here is an example:
Private Sub cmdCalculate_Click()
On Error GoTo ThereWasBadCalculation
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(txtHourlySalary)
WeeklyTime = CDbl(txtWeeklyTime)
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
txtWeeklySalary = FormatNumber(WeeklySalary)
Exit Sub
ThereWasBadCalculation:
MsgBox "There was a problem when performing the calculation"
HourlySalary = 0
Resume Next
End Sub
If there are many variables involved, as is the case for us, you can initialize each. Here an
example:
Private Sub cmdCalculate_Click()
On Error GoTo ThereWasBadCalculation
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
' One of these two lines could produce an error, such as
' if the user types an invalid number
HourlySalary = CDbl(txtHourlySalary)
WeeklyTime = CDbl(txtWeeklyTime)
' If there was an error, the flow would jump to the label
WeeklySalary = HourlySalary * WeeklyTime
txtWeeklySalary = FormatNumber(WeeklySalary)
Exit Sub
ThereWasBadCalculation:
MsgBox "There was a problem when performing the calculation"
HourlySalary = 0
WeeklyTime = 0
Resume Next
End Sub
Types of Error
Introduction
In our introductions to errors, we mostly anticipated only problems related to arithmetic
calculations. In reality, a program can face various categories of bad occurrences. The more
problems you prepare for, the least phone calls and headaches you will have. Problems are
divided in two broad categories.
Syntax Errors
A syntax error occurs if your code tries to perform an operation that the VBA language does not
allow. These errors are probably the easiest to locate because the Code Editor is configured to
point them out at the time you are writing your code.
If you try typing or try inserting an operator or keyword in the wrong place on your code, the
Code Editor would point it out. Here is an example:
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
227
228
In this case, if you were trying to use the Do keyword instead of a data type (probably Double in
this case), the Code Editor would show it right away. This type of error is pointed out for every
keyword and operator you try to use.
Notice that, in the above example, we used a valid keyword but at the wrong time. If you mistype
a keyword or an operator, you would receive an error. Fortunately, the Code Editor is equipped to
know all keywords of the Visual Basic language. Consider the following example:
The programmer mistyped the Mod operator and wrote MAD instead.
If you forget to include a necessary factor in your code, you would get a syntax error. For
example, if you are creating a binary arithmetic expression that expects a second operand after
the operator, you would receive an error. Here is an example:
In this case, the programmer pressed Enter after the Mod operator, as if the expression was
complete. This resulted in an error.
These are just a few types of syntax errors you may encounter. As mentioned already, if you work
in Microsoft Visual Basic to write your code, most of these errors are easy to detect and fix.
Run-Time Errors
A run-time error occurs when your application tries to do something that the operating system
does not allow. In some cases, only your application would crash (Microsoft Excel may stop
working). In some other cases, the user may receive a more serious error. As its name indicates,
a run-time error occurs when the program runs; that is, after you have created your application.
Fortunately, during the testing phase, you may encounter some of the errors so you can fix them
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
before distributing your application. Some other errors may not occur even if you test your
application. They may occur to the users after you have distributed your application. For example,
you can create a car rental application that is able to display pictures 100% of the time on your
computer while locating them from the E: drive. Without paying attention, after distributing your
application, the user's computer may not have an E: drive and, when trying to display the
pictures, the application may crash.
Examples of run-time errors are:
a. Trying to use computer memory that is not available
b. Performing a calculation that the computer hardware (for example the processor) does not
allow. An example is division by 0
c. Trying to use or load a library that is not available or is not accessible, for any reason
d. Performing an arithmetic operation on two incompatible types (such as trying to assign to an
Integer variable the result of adding a string to a Double value)
e. Using a loop that was not properly initialized
f. Trying to access a picture not accessible. Maybe the path specified for the picture is wrong.
Maybe your code gives the wrong extension to the file, even though the file exists
g. Accessing a value beyond the allowable range. For example, using a Byte variable to assign a
performed operation that produces a value the variable cannot hold
As you may imagine, because run-time errors occur after the application has been described as
ready, some of these errors can be difficult to identify. Some other errors depend on the platform
that is running the application (the operating system, the processor, the version of the
application, the (available) memory, etc).
As you can see, this is error number 13. Because there are many types of errors, there are also
many numbers, so much that we cannot review all of them. We can only mention some of them
when we encounter them.
When a program runs, to find out what type of error occurred, you can question the Number
property of the Err object to find out whether the error that has just occurred holds this or that
number. To do this, you can use an If...Then conditional statement to check the number. You can
then display the necessary message to the user. Here is an example:
Private Sub cmdCalculate_Click()
On Error GoTo WrongValue
Dim HourlySalary As Double, WeeklyTime As Double
Dim WeeklySalary As Double
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
229
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
230
2. In the Controls section, click Insert and, in the Form Controls section, click Button (Form
Control)
3. Click an empty on the TimeSheet worksheet
4. On the Assign Macro dialog box, set the Macro Name to btnSubmitTimeSheet_Click
5. Click New
6. Implement the event as follows:
Sub btnSubmitTimeSheet_Click()
On Error GoTo btnSubmitTimeSheet_Error
' This variable will help us check the rows
Dim CurrentRow As Integer
' This variable will get the employee # from the payroll
Dim PayrollEmployeeNumber As String
' This variable will get the employee # from the time sheet
Dim TimeSheetEmployeeNumber As String
' These 2 variables will get the date values from the time sheet
Dim StartDate As Date, EndDate As Date
' These variables represent the time worked from the time sheet
Dim Week1Monday As Double, Week1Tuesday As Double
Dim Week1Wednesday As Double, Week1Thursday As Double
Dim Week1Friday As Double, Week1Saturday As Double
Dim Week1Sunday As Double, Week2Monday As Double
Dim Week2Tuesday As Double, Week2Wednesday As Double
Dim Week2Thursday As Double, Week2Friday As Double
Dim Week2Saturday As Double, Week2Sunday As Double
' We will check the records starting at Row 8
CurrentRow = 8
' Get the employee number from the time sheet
TimeSheetEmployeeNumber = Worksheets("TimeSheet").Range("C6")
' Get the starting date from the time sheet
StartDate = CDate(Worksheets("TimeSheet").Range("C8"))
' Add 2 weeks to the starting date
EndDate = DateAdd("d", 13, StartDate)
' Get the time worked for each day
Week1Monday = CDbl(Worksheets("TimeSheet").Range("C11"))
Week1Tuesday = CDbl(Worksheets("TimeSheet").Range("D11"))
Week1Wednesday = CDbl(Worksheets("TimeSheet").Range("E11"))
Week1Thursday = CDbl(Worksheets("TimeSheet").Range("F11").Value)
Week1Friday = CDbl(Worksheets("TimeSheet").Range("G11").Value)
Week1Saturday = CDbl(Worksheets("TimeSheet").Range("H11").Value)
Week1Sunday = CDbl(Worksheets("TimeSheet").Range("I11").Value)
Week2Monday = CDbl(Worksheets("TimeSheet").Range("C12").Value)
Week2Tuesday = CDbl(Worksheets("TimeSheet").Range("D12").Value)
Week2Wednesday = CDbl(Worksheets("TimeSheet").Range("E12").Value)
Week2Thursday = CDbl(Worksheets("TimeSheet").Range("F12").Value)
Week2Friday = CDbl(Worksheets("TimeSheet").Range("G12").Value)
Week2Saturday = CDbl(Worksheets("TimeSheet").Range("H12").Value)
Week2Sunday = CDbl(Worksheets("TimeSheet").Range("I12").Value)
' Get ready to check each employee number from the payroll
Do
' To process a payroll, an employee from the Accounting department
' enters an employee's employee number
' Get that employee number from the payroll
PayrollEmployeeNumber = Worksheets("Payroll").Cells(CurrentRow, 8).Value
' Check all records from the Payroll
' If you find an empty cell in the columns for the eemployee number,
' this means that there is no record in that row.
' If there is no record, ...
If PayrollEmployeeNumber = "" Then
' ... fill out that record with values from the time sheet
Worksheets("Payroll").Cells(CurrentRow, 2) = TimeSheetEmployeeNumber
Worksheets("Payroll").Cells(CurrentRow, 3) = StartDate
Worksheets("Payroll").Cells(CurrentRow, 4) = EndDate
Worksheets("Payroll").Cells(CurrentRow, 5) = Week1Monday
Worksheets("Payroll").Cells(CurrentRow, 6) = Week1Tuesday
Worksheets("Payroll").Cells(CurrentRow, 7) = Week1Wednesday
Worksheets("Payroll").Cells(CurrentRow, 8) = Week1Thursday
Worksheets("Payroll").Cells(CurrentRow, 9) = Week1Friday
Worksheets("Payroll").Cells(CurrentRow, 10) = Week1Saturday
Worksheets("Payroll").Cells(CurrentRow, 11) = Week1Sunday
Worksheets("Payroll").Cells(CurrentRow, 12) = Week2Monday
Worksheets("Payroll").Cells(CurrentRow, 13) = Week2Tuesday
Worksheets("Payroll").Cells(CurrentRow, 14) = Week2Wednesday
Worksheets("Payroll").Cells(CurrentRow, 15) = Week2Thursday
Worksheets("Payroll").Cells(CurrentRow, 16) = Week2Friday
Worksheets("Payroll").Cells(CurrentRow, 17) = Week2Saturday
Worksheets("Payroll").Cells(CurrentRow, 18) = Week2Sunday
Exit Do
End If
' If you found a record, increase the row count by 1 ...
CurrentRow = CurrentRow + 1
' ... and check the next record
' Continue until the next 93 records
Loop While CurrentRow <= 93
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
231
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
232
233
Probably the simplest action you can perform in the Immediate window consists of testing an
expression. For example, you can write an arithmetic operation and examine its result. To do this,
in the Immediate window, type the question mark "?" followed by the expression and press Enter.
Here is an example that tests the result of 275.85 + 88.26:
One of the most basic actions you can perform in the Immediate window consists of testing a
built-in function. To do this, type ? followed by the name of the function and its arguments, if any.
For example, to test the UCase$ function, in the Immediate window, you could type:
? UCase("Rpublique d'Afrique du Sud")
After typing the function and pressing Enter, the result would display in the next line:
In the same way, you can create a more elaborate expression and test its value in the Immediate
window. You can also pass a value, such as a date, that can easily be converted to a string.
Previous
http://www.functionx.com/vbaexcel/Lesson26.htm#Error
Next
234
Creating a File
Introduction
In Microsoft Excel, instead of a worksheet, you could create a form-based application that your
users would use. If (since) you have already used Windows-based applications, you are surely
familiar with data entry on a form, in which case you use Windows controls.
File processing is the ability to store the values of a document in the computer so you can
retrieve such values another time.
File processing is the ability to save values from an application and be able to get those values
back when needed. The VBA language supports file processing.
http://www.functionx.com/vbaexcel/Lesson27.htm
235
http://www.functionx.com/vbaexcel/Lesson27.htm
236
Daily
Weekly
Monthly
Weekend
Economy
35.95
32.75
28.95
24.95
Compact
39.95
35.75
32.95
28.95
Standard
45.95
39.75
35.95
32.95
Full Size
49.95
42.75
38.95
35.95
Mini Van
55.95
50.75
45.95
42.95
SUV
55.95
50.75
45.95
42.95
Truck
42.75
38.75
35.95
32.95
Van
69.95
62.75
55.95
52.95
http://www.functionx.com/vbaexcel/Lesson27.htm
237
Control
(Name)
Caption/Text
Other Properties
Label
Processed By
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Label
Car Selected
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Label
Employee #:
Text Box
txtEmployeeNumber
Text Box
txtEmployeeName
Label
Text Box
Tag Number:
txtTagNumber
Label
Combo Box
Condition:
cbxCarConditions
Label
Processed For
Label
Make:
Text Box
txtMake
Label
Text Box
Driver's Lic. #:
txtDrvLicenseNbr
Label
Text Box
Model:
txtModel
Label
Text Box
Name:
txtCustomerName
Label
Text Box
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Year:
txtCarYear
TextAlign: 3 - fmTextAlignRight
http://www.functionx.com/vbaexcel/Lesson27.htm
Label
Combo Box
Label
Text Box
Address:
txtAddress
Label
Text Box
Mileage Start:
txtMileageStart
Label
Text Box
txtMileageEnd
txtCity
Order Evaluation
Label
State:
ZIP Code:
txtZIPCode
Label
Text Box
Rate Applied:
txtRateApplied
Label
Text Box
24.95
txtTaxRate
5.75
Days:
txtDays
Label
txtTaxAmount
End Date:
Sub-Total:
txtSubTotal
0.00
TextAlign: 3 - fmTextAlignRight
Order Total:
txtOrderTotal
Label
Text Box
TextAlign: 3 - fmTextAlignRight
txtEndDate
Label
Text Box
0.00
txtStartDate
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Start Date:
Label
Text Box
0
Tax Amount:
Label
Text Box
TextAlign: 3 - fmTextAlignRight
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Tax Rate:
Label
Text Box
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
txtState
Label
Text Box
TextAlign: 3 - fmTextAlignRight
City:
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Mileage End:
Label
Text Box
238
Tank Level:
cbxTankLevels
0.00
TextAlign: 3 - fmTextAlignRight
Receipt #:
txtReceiptNumber
Save
44. Right-click the Employee Number text box and click View Code
45. In the Procedure combo box, select Enter
46. Implement the event as follows:
Private Sub txtEmployeeNumber_Enter()
REM When the Employee # has focus, activate the Employees worksheet
Worksheets(2).Activate
End Sub
47. In the Procedure combo box, select Exit
48. Implement the event as follows:
Private Sub txtEmployeeNumber_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo txtEmployeeNumber_Error
' Check if the user left the Employee Number empty
If txtEmployeeNumber.Text = "" Then
' If so, put leave the Employee Name empty
txtEmployeeName.Text = ""
Else
' If the user entered a valid employee #, use the Microsoft Excel's
' VLOOKUP() function to get the corresponding employee name
' We are using the range of cells from B7 to E13 but you can use a
' range of your choice as long as it contains the employees records
txtEmployeeName.Text = _
Application.WorksheetFunction.VLookup(txtEmployeeNumber.Text, _
Worksheets(2).Range("B7:E13"), 4, False)
End If
Exit Sub
http://www.functionx.com/vbaexcel/Lesson27.htm
txtEmployeeNumber_Error:
' If the user entered an invalid employee #, put Unknown in the name
If Err.Number = 1004 Then
txtEmployeeNumber.Text = ""
txtEmployeeName.Text = "Unknown clerk"
End If
End Sub
49. In the Object combo box, select txtTagNumber
50. In the Procedure combo box, select Enter
51. Implement the event as follows:
Private Sub txtTagNumber_Enter()
Worksheets(4).Activate
End Sub
52. In the Procedure combo box, select Exit
53. Implement the event as follows:
Private Sub txtTagNumber_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo txtTagNumber_Error
' Check if the user left the Tag Number text box empty
If txtTagNumber.Text = "" Then
' If so, leave the car information empty
txtTagNumber.Text = ""
txtMake.Text = ""
txtModel.Text = ""
txtCarYear.Text = ""
Else
' If the user entered a valid Tag Number, use the Microsoft Excel's
' VLOOKUP() function to get the corresponding car information
txtMake.Text = _
Application.WorksheetFunction.VLookup(txtTagNumber.Text, _
Worksheets(4).Range("B6:I26"), 2, False)
txtModel.Text = _
Application.WorksheetFunction.VLookup(txtTagNumber.Text, _
Worksheets(4).Range("B6:I26"), 3, False)
txtCarYear.Text = _
Application.WorksheetFunction.VLookup(txtTagNumber.Text, _
Worksheets(4).Range("B6:I26"), 4, False)
End If
Exit Sub
txtTagNumber_Error:
' If the user entered an invalid tag #, leave the Tag Number empty
If Err.Number = 1004 Then
txtTagNumber.Text = ""
txtMake.Text = ""
txtModel.Text = ""
txtCarYear.Text = ""
End If
End Sub
54. In the Object combo box, select txtDrvLicenseNbr
55. In the Procedure combo box, select Enter
56. Implement the event as follows:
Private Sub txtDrvLicenseNbr_Enter()
Worksheets(3).Activate
End Sub
57. In the Procedure combo box, select Exit
58. Implement the event as follows:
Private Sub txtDrvLicenseNbr_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo txtDrvLicenseNbr_Error
If txtDrvLicenseNbr.Text = "" Then
txtCustomerName.Text = ""
txtAddress.Text = ""
txtCity.Text = ""
txtState.Text = ""
txtZIPCode.Text = ""
Else
txtCustomerName.Text = _
Application.WorksheetFunction.VLookup(txtDrvLicenseNbr.Text, _
http://www.functionx.com/vbaexcel/Lesson27.htm
239
Worksheets(3).Range("B6:I26"), 2, False)
txtAddress.Text = _
Application.WorksheetFunction.VLookup(txtDrvLicenseNbr.Text,
Worksheets(3).Range("B6:I26"), 3, False)
txtCity.Text = _
Application.WorksheetFunction.VLookup(txtDrvLicenseNbr.Text,
Worksheets(3).Range("B6:I26"), 4, False)
txtState.Text = _
Application.WorksheetFunction.VLookup(txtDrvLicenseNbr.Text,
Worksheets(3).Range("B6:I26"), 5, False)
txtZIPCode.Text = _
Application.WorksheetFunction.VLookup(txtDrvLicenseNbr.Text,
Worksheets(3).Range("B6:I26"), 6, False)
End If
Exit Sub
txtDrvLicenseNbr_Error:
If Err.Number = 1004 Then
txtDrvLicenseNbr.Text = ""
txtCustomerName.Text = ""
txtAddress.Text = ""
txtCity.Text = ""
txtState.Text = ""
txtZIPCode.Text = ""
End If
End Sub
59. In the Object combo box, select txtRateApplied
60. In the Procedure combo box, select Enter
61. Implement the event as follows:
Private Sub txtRateApplied_Enter()
Worksheets(5).Activate
End Sub
62. In the Object combo box, select UserForm
63. In the Procedure combo box, select Activate
64. Implement the event as follows:
Private Sub ResetRentalOrder()
Dim strRandomNumber As String
' Fill the Conditions combo box
cbxCarConditions.AddItem "Needs Repair"
cbxCarConditions.AddItem "Drivable"
cbxCarConditions.AddItem "Excellent"
' Fill the Tank Level
cbxTankLevels.AddItem
cbxTankLevels.AddItem
cbxTankLevels.AddItem
cbxTankLevels.AddItem
cbxTankLevels.AddItem
combo box
"Empty"
"1/4 Empty"
"1/2 Full"
"3/4 Full"
"Full"
http://www.functionx.com/vbaexcel/Lesson27.htm
240
_
txtModel.Text = ""
txtCarYear.Text = ""
cbxTankLevels.Text = ""
txtMileageStart.Text = "0"
txtMileageEnd.Text = "0"
txtRateApplied.Text = "24.95"
txtTaxRate.Text = "5.75"
txtDays.Text = "0"
txtTaxAmount.Text = "0.00"
txtSubTotal.Text = "0.00"
txtOrderTotal.Text = "0.00"
txtNotes.Text = ""
' Display today's date in the date text boxes
txtStartDate = Date
txtEndDate = Date
End Sub
Private Sub UserForm_Activate()
Call ResetRentalOrder
End Sub
65. In the Object combo box, select cmdReset
66. Implement the Click event as follows:
Private Sub cmdReset_Click()
Call ResetRentalOrder
End Sub
67. On the Standard toolbar, click the Save button
68. Return to Microsoft Excel and click the Switchboard tab sheet
69. In the Developer tab of the Ribbon, in the Controls section, click Insert
70. In the ActiveX Controls section, click Command Button
71. Click the worksheet
72. Right-click the new button and click Properties
73. In the properties window, change the following characteristics
(Name): cmdCreateRentalOrder
Caption: Create New Rental Order
74. Right-click the button and click View Code
75. Implement the event as follows:
Private Sub cmdCreateRentalOrder_Click()
frmNewRentalOrder.Show
End Sub
76. Press Ctrl + S to save
File Creation
Before performing file processing, the first action you must perform consists of creating a file. To
support file creation, the VBA provides a procedure named Open. Its syntax is:
Open pathname For Output [Access access] [lock] As [#]filenumber [Len=reclength]
The Open statement takes many factors, some are required and others are not. The Open (the
name of the procedure) word, the For Output expression, and the As # expression are required.
The first argument, pathname, is required. This is a string that can be the name of the file. The
file can have an extension or not. Here is an example:
Open "example.dat"
If you specify only the name of the file, it would be considered in the same folder where the
current workbook is (the workbook that was opened when you called this statement). If you want,
you can provide a complete path for the file. This would include the drive, the (optional) folder(s),
up to the name of the file, with or without extension.
Besides the name of the file or its path, the mode factor is required. This factor specifies the
actual action you want to perform, such as creating a new file or only opening an existing one.
This factor can be one of the following keywords:
Output: The file will be created and ready to receive (normal) values
Binary: The file will be created and ready to receive values in binary format (as combinations
of 1s and 0s)
Append: If the file exists already, it will be opened and new values can be added to the end
http://www.functionx.com/vbaexcel/Lesson27.htm
241
242
Closing a File
When you create a file and start using it, or after opening a file and while you are using it, it uses
memory and consumes (or can be consuming) memory (which could be significant). When you
have finished using the file, you should free the memory it was using and release the resources it
was consuming. To assist you with this, the VBA provides a procedure named Close. Its syntax is:
Close [filenumberlist]
The filenumberlist factor is the filenumber you would have previously used to create or open the
file.
Here is an example of closing a file:
Private Sub cmdSave_Click()
Open "example.dat" For Output As #1
Close #1
End Sub
Printing to a File
After creating a file, you may want to write values to it. To support this, the VBA provides two
procedures. One of them is called Print and its syntax is:
Print #filenumber, [outputlist]
The Print statement takes two factors but only the first is required.
The filenumber factor is the filenumber you would have used to create the file. The filenumber is
followed by a comma.
The outputlist factor can be made of 0, 1 or more parts. Because it is optional, if you do not want
to write a value to the file, leave this part empty. If you want to write a value, type a comma after
the filenumber factor and follow these rules:
If you want to start the value with empty spaces, use the Spc() function and pass an integer
(in the parentheses) that represents the number of empty spaces. For example Spc(4) would
include 4 empty spaces.
This factor is optional, which means you can omit it
Instead of a specific number of empty spaces, you can let the operating system specify a
built-in number of empty spaces. To do this, call the Tab() function as part of your outputlist
factor. The Tab() function specifies the number of columns to include before the value. The
Tab() function can be more useful if you are concerned with the alignment of the value(s)
http://www.functionx.com/vbaexcel/Lesson27.htm
#1,
#1,
#1,
#1,
"James"
"Larenz"
True
#12/08/2008#
Close #1
End Sub
Instead of writing one value per line, you can write more than one value with one statement. To
do this, separate them with either a semi-colon or an empty space. Here is an example:
Private Sub cmdSave_Click()
Open "Employee.txt" For Output As #1
REM The values are separated by a semi-colon
Print #1, "James"; "Larenz"
REM The values are separated by an empty space
Print #1, True #12/08/2008#
Close #1
End Sub
Writing to a File
Besides the Print procedure, the VBA also provides a procedure named Write that can be used to
write one or more values to a file. The syntax of the Write statement is the same as that of
Print:
Write #filenumber, [outputlist]
The filenumber factor is required. It must be the filenumber specified when creating the file.
The outputlist factor is optional. If you want to skip it, type a comma after the filenumber and end
the Write statement. In this case, an empty line would be written to the file. To write the values
to the file, follow these rules:
To start the value with empty spaces, call the Spc() function and pass a number that
represents the number of empty spaces.
This factor is optional, which means you can omit it
To start the value with a specific number of columns, call the Tab() function and pass the
number of columns as argument.
This factor is optional, which means you can omit it
To write a string, include it in double-quotes
To write a number, include it normally
To write a Boolean value, type it as #TRUE# or #FALSE#
To write a null value, type #NULL#
To write a date or time value, type it between # and #
Here is an example of writing some values:
Private Sub cmdSave_Click()
Open "Employee.txt" For Output As #1
Write
Write
Write
Write
Write
Write
#1,
#1,
#1,
#1,
#1,
#1,
"James"
"M"
"Larenz"
#12/08/2008#
24.50
True
Close #1
End Sub
http://www.functionx.com/vbaexcel/Lesson27.htm
243
You can also write values on the same line. To do this, separate them with an empty space, a
comma, or a semi-colon. Here is an example:
Private Sub cmdSave_Click()
Open "Employee.txt" For Output As #1
REM The values are separated by a semi-colon
Write #1, "James"; "M"; "Larenz"
REM The values are separated by a comma
Write #1, #12/08/2008#, 24.50
Write #1, True
Close #1
End Sub
http://www.functionx.com/vbaexcel/Lesson27.htm
244
245
Exit Sub
cmdSave_Error:
MsgBox "There is a problem with the form. It cannot be saved."
Resume Next
End Sub
4. On the Standard toolbar, click the Save button
5. Return to Microsoft Excel and click the Switchboard tab sheet if necessary
6. In the Developer tab of the Ribbon, in the Controls section, click Insert
7. In the ActiveX Controls section, click Command Button
8. Click the worksheet
9. Right-click the new button and click Properties
10. In the properties window, change the following characteristics
(Name): cmdCreateRentalOrder
Caption: Create New Rental Order
11. Right-click the button and click View Code
12. Implement the event as follows:
Private Sub cmdCreateRentalOrder_Click()
frmNewRentalOder.Show
End Sub
13. Press Ctrl + S to save
14. Return to Microsoft Excel
15. In the Controls section of the Ribbon, click the Design Mode button to uncheck it
16. Click the button to display the form
17. Enter some values for a rental order
http://www.functionx.com/vbaexcel/Lesson27.htm
246
Opening a File
Opening a File
Instead of creating a new file, you may want to open an existing file. To support this
operation, the VBA provides a procedure named Open. Its syntax is:
Open pathname For Input [Access access] [lock] As [#]filenumber [Len=reclength]
The Open procedure takes many arguments, some are required and others are not. The
Open word, For Input expression, and the As # expression are required.
The first argument, pathname, is required. This is a string that can be the name of the file. The
file can have an extension or not. Here is an example:
Open "example.dat"
If you specify only the name of the file, the interpreter would look for the file in the same folder
where the current workbook is. If you want, you can provide a complete path for the file. This
would include the drive, the (optional) folder(s), up to the name of the file, with or without
extension.
Besides the name of the file or its path, the mode factor is required. To open a file, the mode
factor can be:
Binary: The file will be opened and its value(s) would be read as (a) binary value(s)
Append: The file will be opened and new values can be added to the end of the existing
values
Input: The file will be opened normally
Random: The will be opened for random access
Here is an example of opening a file:
Private Sub cmdSave_Click()
Open "example.dat" For Input As #1
http://www.functionx.com/vbaexcel/Lesson27.htm
End Sub
247
The access factor is optional. This factor can have one of the following values:
Read: After the file has been opened, values will be read from it
Read Write: Whether the file was created or opened, values can be read from it and/or
written to it
If you decide to specify the access factor, precede its value with the Access keyword.
The lock factor is optional and its possible values can be:
Shared: Other applications can access this file while the current application is accessing it
Lock Read: Other applications are not allowed to access this file while the current application
is reading from it
Lock Read Write: Other applications are not allowed to access this file while the current
application is using it
On the right side of #, type a number, for the filenumber factor, between 1 and 511. Use the
same rules/description we saw for creating a file.
The reclength factor is optional. If the file was opened, this factor specifies the length of the
record that was read.
Control
(Name)
Label
Text Box
Caption/Text
txtReceiptNumber
Open
Label
Order Status:
Text Box
Other Properties
Receipt #:
cbxOrderStatus
http://www.functionx.com/vbaexcel/Lesson27.htm
Label
Processed By
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Label
Car Selected
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Label
Employee #:
Text Box
txtEmployeeNumber
Text Box
txtEmployeeName
Label
Text Box
Tag Number:
txtTagNumber
Label
Combo Box
Condition:
cbxCarConditions
Label
Processed For
Label
Text Box
Make:
txtMake
Label
Text Box
Driver's Lic. #:
txtDrvLicenseNbr
Label
Text Box
Model:
txtModel
Label
Text Box
Name:
txtCustomerName
Label
Text Box
Year:
txtCarYear
Label
Combo Box
cbxTankLevels
Address:
txtAddress
Label
Text Box
Mileage Start:
txtMileageStart
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Mileage End:
txtMileageEnd
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Tank Level:
Label
Text Box
TextAlign: 3 - fmTextAlignRight
City:
txtCity
Label
Order Evaluation
Label
State:
Text Box
ZIP Code:
txtZIPCode
Label
Text Box
Rate Applied:
txtRateApplied
Label
Text Box
24.95
txtTaxRate
5.75
Days:
txtDays
Label
txtTaxAmount
TextAlign: 3 - fmTextAlignRight
End Date:
txtEndDate
Sub-Total:
txtSubTotal
Label
Text Box
0.00
txtStartDate
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Start Date:
Label
Text Box
0
Tax Amount:
Label
Text Box
TextAlign: 3 - fmTextAlignRight
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
Label
Text Box
TextAlign: 3 - fmTextAlignRight
Tax Rate:
Label
Text Box
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
txtState
Label
Text Box
BackColor: &H00808080&
BorderColor: &H00000000&
ForeColor: &H00FFFFFF&
0.00
TextAlign: 3 - fmTextAlignRight
Order Total:
txtOrderTotal
0.00
TextAlign: 3 - fmTextAlignRight
http://www.functionx.com/vbaexcel/Lesson27.htm
248
"Empty"
"1/4 Empty"
"1/2 Full"
"3/4 Full"
"Full"
Sub CalculateRentalOrder()
RateApplied As Double
Days As Integer
SubTotal As Double
TaxRate As Double
TaxAmount As Double
OrderTotal As Double
http://www.functionx.com/vbaexcel/Lesson27.htm
249
Sub cmdOpen_Click()
FirstName As String
LastName As String
IsFullTimeEmployee As Boolean
http://www.functionx.com/vbaexcel/Lesson27.htm
250
This statement takes two factors and both are required. The filenumber is the number you would
have used to open the file. When the Line Input statement is called, it reads a line of text until it
gets to the end of the file. One of the limitations of the Line Input statement is that it has a hard
time reading anything other than text because it may not be able to determine where the line
ends.
When reviewing the ability to write values to a file, we saw that the Print statement writes a
Boolean value as True or False. If you use the Input statement to read such a value, the
interpreter may not be able to read the value. We saw that an alternative to the Print statement
was Write. We saw that, among the differences between Print and Write, the latter writes
Boolean values using the # symbol. This makes it possible for the interpreter to easily read such a
value. For these reasons, in most cases, it may be a better idea to prefer using the Write
statement when writing values other than strings to a file.
EmployeeNumber As String
EmployeeName As String, DrvLicenseNbr As String
CustomerName As String, Address As String
City As String, State As String
ZIPCode As String, StartDate As String
EndDate As String, TagNumber As String
CarConditions As String, Make As String
Model As String, CarYear As String
TankLevels As String, MileageStart As String
MileageEnd As String, RateApplied As String
TaxRate As String, Days As String
TaxAmount As String, SubTotal As String
OrderTotal As String, OrderStatus As String
Notes As String
Rem We are not doing any validation here because there are
'
issues we haven't explored yet. For example, we haven't yet
'
learned how to check the list of files in a directory.
'
We also haven't yet learned how to check whether a file
'
exists in a directory.
Open "C:\Bethesda Car Rental\" & _
txtReceiptNumber.Text & ".bcr" For Input As #1
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
Input
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
EmployeeNumber
EmployeeName
DrvLicenseNbr
CustomerName
Address
City
State
ZIPCode
StartDate
EndDate
TagNumber
CarConditions
Make
Model
CarYear
TankLevels
MileageStart
MileageEnd
RateApplied
TaxRate
Days
TaxAmount
SubTotal
OrderTotal
OrderStatus
Notes
txtEmployeeNumber.Text = EmployeeNumber
txtEmployeeName.Text = EmployeeName
txtDrvLicenseNbr.Text = DrvLicenseNbr
txtCustomerName.Text = CustomerName
txtAddress.Text = Address
txtCity.Text = City
txtState.Text = State
txtZIPCode.Text = ZIPCode
txtStartDate.Text = StartDate
txtEndDate.Text = EndDate
txtTagNumber.Text = TagNumber
cbxCarConditions.Text = CarConditions
http://www.functionx.com/vbaexcel/Lesson27.htm
251
txtMake.Text = Make
txtModel.Text = Model
txtCarYear.Text = CarYear
cbxTankLevels.Text = TankLevels
txtMileageStart.Text = MileageStart
txtMileageEnd.Text = MileageEnd
txtRateApplied.Text = RateApplied
txtTaxRate.Text = TaxRate
txtDays.Text = Days
txtTaxAmount.Text = TaxAmount
txtSubTotal.Text = SubTotal
txtOrderTotal.Text = OrderTotal
cbxOrderStatus.Text = OrderStatus
txtNotes.Text = Notes
Close #1
Exit Sub
cmdOpen_Error:
MsgBox "There was a problem when trying to open the file."
Resume Next
End Sub
3. In the Object combo box, select cmdUpdateRentalOrder
4. Implement the Click event as follows:
Private Sub cmdUpdateRentalOrder_Click()
On Error GoTo cmdSave_Error
Open "C:\Bethesda Car Rental\" & txtReceiptNumber.Text & _
".bcr" For Output As #1
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
Write
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
#1,
txtEmployeeNumber.Text
txtEmployeeName.Text
txtDrvLicenseNbr.Text
txtCustomerName.Text
txtAddress.Text
txtCity.Text
txtState.Text
txtZIPCode.Text
txtStartDate.Text
txtEndDate.Text
txtTagNumber.Text
cbxCarConditions.Text
txtMake.Text
txtModel.Text
txtCarYear.Text
cbxTankLevels.Text
txtMileageStart.Text
txtMileageEnd.Text
txtRateApplied.Text
txtTaxRate.Text
txtDays.Text
txtTaxAmount.Text
txtSubTotal.Text
txtOrderTotal.Text
cbxCarConditions.Text
txtNotes.Text
Close #1
Exit Sub
cmdSave_Error:
MsgBox "There is a problem with the form. " & _
"The rental order cannot be updated."
Resume Next
End Sub
5. On the Standard toolbar, click the Save button
6. Return to Microsoft Excel
7. Click the Switchboard tab sheet
8. In the Developer tab of the Ribbon, in the Controls section, click Insert
9. In the ActiveX Controls section, click Command Button
10. Click the worksheet
11. Right-click the new button and click Properties
12. In the properties window, change the following characteristics
(Name): cmdOpenRentalOrder
Caption: Open Existing Rental Order
http://www.functionx.com/vbaexcel/Lesson27.htm
252
253
13. Right-click the open Existing Rental Order button and click View Code
14. Implement the event as follows:
Private Sub cmdOpenRentalOrder_Click()
frmRentalOrderReview.Show
End Sub
15. Press Ctrl + S to save
16. Close Microsoft Visual Basic
17. In the Controls section of the Ribbon, click the Design Mode button to uncheck it
18. Click the button to display the form
19. Click the Receipt # text box
20. Type a receipt number of one of the rental orders you created earlier
21. Click the Open button
22. Select a different option in the order status combo box
23. Change the value of mileage end, the end date and the days
http://www.functionx.com/vbaexcel/Lesson27.htm
254
Previous
http://www.functionx.com/vbaexcel/Lesson27.htm
Home
255
Fundamentals of Dates
Introduction
The Visual Basic language has a strong support for date values. It is equipped with a data type
named Date. To create and manipulate dates, you have various options. To declare a date
variable, you use the Date data type. To support date and time-based operations, the Visual
Basic language provides various functions. Besides the Visual Basic language, the Microsoft Excel
library provides its own support for dates and times.
If you already know the components of the date value you want to use, you can include them
between two # signs but following the rules of a date format from the Regional Settings of Control
Panel. Here is an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = # 02/08/2003 #
MsgBox("Date Hired: " & DateHired)
End Sub
This would produce:
Full Name
Short
Name
January
Jan
February
Feb
March
Mar
April
Apr
May
May
June
Jun
July
Jul
August
Aug
http://www.functionx.com/vbaexcel/topics/datetime.htm
September
Sep
10
October
Oct
11
November
Nov
12
December
Dec
Full Name
Short
Name
Sunday
Sun
Monday
Mon
Tuesday
Tue
Wednesday
Wed
Thursday
Thu
Friday
Fri
Saturday
Sat
These are the default in US English. In most calculations, the Visual Basic language allows you to
specify what day should be the first in a week.
The year is expressed as a numeric value.
Dates Formats
In US English, to express a date value, you can use one of the following formats:
mm-dd-yy
mm-dd-yyyy
You must start the date with a number that represents the month (a number from 1 to 12). After
the month value, enter -. Then type the day value as a number between 1 and 28, 29, 30, or 31
depending on the month and the (leap) year. Follow it with -. End the value with a year in 2 or 4
digits. Here are examples 06-12-08 or 10-08-2006.
You can also use one of the following formats:
dd-mmm-yy
dd mmm yy
dd-mmmm-yy
dd mmmm yy
dd-mmm-yyyy
dd mmm yyyy
dd-mmmm-yyyy
dd mmmm yyyy
This time, enter the day value followed either by an empty space or -. Follow with the short name
of the month in the mmm placeholder or the complete name of the month for the mmmm
placeholder, followed by either an empty space or -. End the value with the year, using 2 or 4
digits.
As you may know already, in US English, you can start a date with the month. In this case, you
can use one of the following formats:
mmm dd, yy
mmm dd, yyyy
mmmm dd, yy
mmmm dd, yyyy
As seen with the previous formats, mmm represents the short name of a month and mmmm
represents the full name of a month. As mentioned already, the dd day can be expressed with 1 or
2 digits and the single digit can have a leading 0. After the day value, (you must) enter a comma
followed by the year either with 2 or 4 digits.
A Date Value
We have seen that, when creating a date, you can include its value between # signs. An
alternative is to provide a date as a string. To support this, the Visual Basic language provides a
function named DateValue. Its syntax is:
http://www.functionx.com/vbaexcel/topics/datetime.htm
256
A Date as Serial
An alternative to initializing a date variable is to use a function named DateSerial. Its syntax is:
Function DateSerial(ByVal [Year] As Integer, _
ByVal [Month] As Integer, _
ByVal [Day] As Integer) As Variant
As you can see, this function allows you to specify the year, the month, and the day of a date
value, of course without the # signs. When it has been called, this function returns a Variant
value, which can be converted into a Date. Here is an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = DateSerial(2003, 02, 08)
MsgBox("Date Hired: " & DateHired)
End Sub
This would produce:
When passing the values to this function, you must restrict each component to the allowable
range of values. You can pass the year with two digits from 0 to 99. Here is an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = DateSerial(03, 2, 8)
MsgBox("Date Hired: " & DateHired)
End Sub
If you pass the year as a value between 0 and 99, the interpreter would refer to the clock on the
computer to get the century. At the time of this writing (in 2009), the century would be 20 and
the specified year would be added, which would produce 2003. To be more precise and reduce any
confusion, you should always pass the year with 4 digits.
The month should (must) be a value between 1 and 12. If you pass a value higher than 12, the
interpreter would calculate the remainder of that number by 12 (that number MOD 12 = ?). The
result of the integer division would be used as the number of years and added to the first
argument. The remainder would be used as the month of the date value. For example, if you pass
the month as 18, the integer division would produce 1, so 1 year would be added to the first
argument. The remainder is 6 (18 MOD 12 = 6); so the month would be used as 6 (June). Here is
an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = DateSerial(2003, 18, 8)
MsgBox("Date Hired: " & DateHired)
End Sub
This would produce:
http://www.functionx.com/vbaexcel/topics/datetime.htm
257
258
As another example, if you pass the month as 226, the integer division (226 \ 12) produces 18
and that number would be added to the first argument (2003 + 18 = 2021). The remainder of
226 to 12 (226 MOD 12 = 10) is 10 and that would be used as the month. Here is an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = DateSerial(2003, 226, 8)
MsgBox("Date Hired: " & DateHired)
End Sub
This would produce:
If the month is passed as 0, it is considered 12 (December) of the previous year. If the month is
passed as -1, it is considered 11 (November) of the previous year and so on. If the month is
passed as a number lower than -11, the interpreter would calculate its integer division to 12, add
1 to that result, use that number as the year, calculate the remainder to 12, and use that result
as the month.
Depending on the month, the value of the day argument can be passed as a number between 1
and 28, between 1 and 29, between 1 and 30, or between 1 and 31. If the day argument is
passed as a number lower than 1 or higher than 31, the interpreter uses the first day of the
month passed as the second argument. This is 1.
If the day is passed as -1, the day is considered the last day of the previous month of the Month
argument. For example, if the Month argument is passed as 4 (April) and the Day argument is
passed as -1, the interpreter would use 31 as the day because the last day of March is 31.
If the Month argument is passed as 3 (March) and the Day argument is passed as -1, the
interpreter would refer to the Year argument to determine whether the year is leap or not. This
would allow the interpreter to use either 28 or 29 for the day value. The interpreter uses this
algorithm for any day value passed as the third argument when the number is lower than 1.
If the Day argument is passed with a value higher than 28, 29, 30, or 31, the interpreter uses
this same algorithm in reverse order to determine the month and the day.
Besides the Visual Basic's DateSerial() function, the Microsoft Excel library provides a function
named DATE
When using this function, pass the values of the year, the month, and the day. You can use
exactly the rules we reviewed for the DateSerial() function. Here is an example:
Sub Exercise()
Range("B2").FormulaR1C1 = "=DATE(2003, 226, 8)"
End Sub
This would produce:
http://www.functionx.com/vbaexcel/topics/datetime.htm
259
Besides the Visual Language's Year() function, the Microsoft Excel library provides a function
named YEAR that can be used to get the year value of a date. The date must be provided in the
format the DATE() function.
http://www.functionx.com/vbaexcel/topics/datetime.htm
DateHired = #2/8/2004#
MsgBox ("Month hired " & Month(DateHired))
End Sub
This would produce:
Besides the Visual Basic's Month() function, you can use the MONTH() function of the Microsoft
Excel library. This function takes one argument as the type of date produced by a call to the
DATE() function.
As mentioned already, the Month() function produces a numeric value that represents the month
of a date. Instead of getting the numeric index of the month of a date, if you want to get the
name of the month, you can call the Visual Basic function named MonthName. Its syntax is:
Function MonthName(ByVal Month As Integer, _
Optional ByVal Abbreviate As Boolean = False) As String
This function takes one required and one optional arguments. The required argument must
represent the value of a month. If it is valid, this function returns the corresponding name. Here
is an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = #2/8/2004#
MsgBox("Day hired " & MonthName(Month(DateHired)))
End Sub
This would produce:
The second argument allows you to specify whether you want to get the complete or the short
name. The default is the complete name, in which case the default value of the argument is
False. If you want to get the short name, pass the second argument as True. Here is an example:
Public Sub Exercise
Dim DateHired As Date
DateHired = #2/8/2004#
MsgBox("Month hired " & MonthName(Month(DateHired), True))
End Sub
This would produce:
http://www.functionx.com/vbaexcel/topics/datetime.htm
260
DateHired = #2/8/2004#
MsgBox("Day hired " & Day(DateHired))
End Sub
This would produce:
If you pass a negative value or a value higher than 7, you would receive an error.
The second argument allows you to specify whether you want to get the complete or the short
name. The default value of this argument is False, which produces a complete name. If you want
a short name, pass the second argument as True. Here is an example:
Public Sub Exercise
MsgBox("Day hired: " & WeekdayName(4, True))
End Sub
As mentioned already, the Visual Basic language allows you to specify what days should be the
first day of the week. This is the role of the third argument.
http://www.functionx.com/vbaexcel/topics/datetime.htm
261
262
To support these primary formats, the Visual Basic language provides a function named
FormatDateTime. Its syntax is:
Function FormatDateTime(
ByVal Expression As Variant,
Optional ByVal NamedFormat As Integer = 0
) As String
The first argument of this function must be a valid Date value. The second argument is an
integer. For a date, this argument can be 1 or 2. Here is an example:
Public Sub Exercise
Dim DateHired$
DateHired$ = FormatDateTime("22-Aug-2006", 1)
MsgBox("Date Hired: " & DateHired)
End Sub
This would produce:
http://www.functionx.com/vbaexcel/topics/datetime.htm
263
http://www.functionx.com/vbaexcel/topics/datetime.htm
264
This function takes three arguments as the hour, the minute, and the second.
http://www.functionx.com/vbaexcel/topics/datetime.htm
265
Used To Add
Second
Minute
Hour
Numeric Weekday
ww
Day
Month
Quarter
yyyy
Year
The Number argument specifies the number of Interval units you want to add to the
DateValue value. If you set it as positive, its value will be added. Here are
examples:
Public Sub Exercise
Dim LoanStartDate As Date
Dim DepositTime As Date
LoanStartDate = #6/10/1998#
DepositTime = TimeValue("7:14:00")
MsgBox ("Loan Length: " & DateAdd("yyyy", 5, LoanStartDate))
MsgBox ("Time Ready: " & DateAdd("h", 8, DepositTime))
End Sub
This would produce:
http://www.functionx.com/vbaexcel/topics/datetime.htm
266
_
As [ DateInterval | String ], _
Variant, _
Variant, _
DayOfWeek As Interger = 1, _
WeekOfYear As Integer = 1 _
This function takes five arguments, three of which are required and two are
optional.
The Date1 argument can be the start date or start time. The Date2 argument can
be the end date or end time. These two arguments can also be reversed, in which
case the Date2 argument can be the start date or start time and the Date1
argument would be the end date or end time. These two values must be valid date
or time values
The Interval argument specifies the type of value you want as a result. This
argument will be enclosed between double quotes and can have one of the following
values:
Interval
Used To Get
Second
Minute
http://www.functionx.com/vbaexcel/topics/datetime.htm
Hour
Numeric Weekday
ww
Day
Month
Quarter
yyyy
267
Year
Here is an example:
Public Sub Exercise
Dim LoanStartDate As Date
Dim LoanEndDate As Date
Dim Months As Long
LoanStartDate = #8/12/2003#
LoanEndDate = #10/5/2008#
Months = DateDiff("m", LoanStartDate, LoanEndDate)
MsgBox("Loan Start Date: " & vbTab & LoanStartDate & vbCrLf & _
"Loan End Date: " & vbTab & LoanEndDate & vbCrLf & _
"Loan Length: " & vbTab & Months & " months")
End Sub
This would produce:
By default, the days of a week are counted starting on Sunday. If you want to start
counting those days on another day, supply the Option1 argument using one of the
following
values:
vbSunday,
vbMonday,
vbTuesday,
vbWednesday,
vbThursday, vbFriday, vbSaturday. There are other variances to that argument.
If your calculation involves weeks or finding the number of weeks, by default, the
weeks are counted starting January 1st. If you want to count your weeks starting at
a different date, use the Option2 argument to specify where the function should
start.
We saw that we could use the DateDiff() function to get the difference between
two date or time values. The first argument can be specified as a string. A better
idea is to use a member of the DateInterval enumeration. The members are:
Value
Constant
Value
Description
vbUseSystemDayOfWeek
vbSunday
vbMonday
Monday
vbTuesday
Tuesday
vbWednesday
Wednesday
vbThursday
Thursday
vbFriday
Friday
vbSaturday
Saturday
By default, the first week of a year is the one that includes January 1st of that year.
This is how it is considered in the regular date-based calculations. If you want to
change this default setting, you can use the last argument of the DateDiff()
function. The value of this argument can be:
Value
vbUseSystem
Constant
Value
Description
The interpreter will refer to the
operating system to find out
what day should be the first.
This should be the week that
includes January 1st
http://www.functionx.com/vbaexcel/topics/datetime.htm
vbFirstJan1
vbFirstFourDays
vbFirstFullWeek
To calculate the number of days between two dates considering that a year has 360
days, you can use the DAYS360() function of the Microsoft Excel library.
Home
http://www.functionx.com/vbaexcel/topics/datetime.htm
268
269
Description
This is an example of an application used by a fictitious car repair shop. The starting spreadsheet
allows an employee to register a repair order. This includes a customer's name and the car.
To process an order, the employee must provide a list of auto parts that would have been used to
repair the car. Then the clerk must enter the list of jobs that were performed for the order.
http://www.functionx.com/vbaexcel/applications/cpar.htm
270
32. On the worksheet, right-click the New Auto Repair button and click View Code
33. Write the code as follows:
Option Explicit
Private AutoRepairExists As Boolean
Private Sub cmdNewAutoRepair_Click()
AutoRepairExists = False
Range("D4") = "": Range("D5") = Date: Range("D8") = ""
Range("D9") = "": Range("D10") = "": Range("G10") = ""
Range("J10") = "": Range("D12") = "": Range("G12") = ""
Range("J12") = "": Range("D13") = "": Range("G13") = ""
Range("B16") = "": Range("C16") = "": Range("H16") = ""
Range("I16") = "": Range("J16") = "": Range("B17") = ""
Range("C17") = "": Range("H17") = "": Range("I17") = ""
Range("B18") = "": Range("C18") = "": Range("H18") = ""
Range("I18") = "": Range("B19") = "": Range("C19") = ""
Range("H19") = "": Range("I19") = "": Range("B20") = ""
Range("C20") = "": Range("H20") = "": Range("I20") = ""
Range("B21") = "": Range("C21") = "": Range("H21") = ""
Range("I21") = "": Range("B24") = "": Range("J24") = ""
Range("B25") = "": Range("J25") = "": Range("B26") = ""
Range("J26") = "": Range("B27") = "": Range("J27") = ""
Range("B28") = "": Range("J28") = "": Range("B29") = ""
Range("J29") = "": Range("J33") = "5.75%"
Range("D4").Select
End Sub
34. In the Object combo box, select cmdOpenAutoRepair
35. Implement its Click event as follows:
http://www.functionx.com/vbaexcel/applications/cpar.htm
271
Home
http://www.functionx.com/vbaexcel/applications/cpar.htm