Professional Documents
Culture Documents
MACROS
EXPERIENCE THE JOURNEY
R. BHAARATH
PRE-REQUISITE:
This course Material is intended for all users who have sufficient
Knowledge of Microsoft Excel and possess a fair degree of exposure to
its various features like
COVER
A Scenic view during the journey from Hassan to Mangalore
COPYRIGHT 2008-2015
No Part of this Course Material Publication may be reproduced and / or
used for any commercial purposes whatsoever without the express
permission of Bharath Infotech. Bharath Infotech reserves the sole
rights to the Intellectual property of this material.
Table of Contents
PRE-REQUISITE: ............................................................................................................. 2
Automation using Macros ......................................... 6
Macros ....................................................................................................................... 6
Macro Security ........................................................................................................... 7
What Is a Digital Certificate? ..................................................................................... 8
What Is a Signature? Why Do We Need Them? ......................................................... 8
How to Obtain a Digital Signature? ............................................................................ 9
To Install the SelfCert Tool ...................................................................................... 10
Locating SelfCert.exe ............................................................................................... 10
Create a Digital Certificate Using SelfCert.exe ......................................................... 10
The Macro Recorder ................................................................................................. 13
Relative and Absolute Recording.............................................................................. 14
Where Macros Reside............................................................................................... 15
Locating the Personal Macro Workbook ................................................................... 16
The Dangers of Macro Shortcuts .............................................................................. 17
Programming Spreadsheets with VBA .................... 18
The Visual Basic Editor............................................................................................ 18
Parts of the VBA Editor............................................................................................ 19
Modules and Macros ................................................................................................ 21
Understanding Macro Code .................................... 22
The Anatomy of a Macro .......................................................................................... 22
Running the Macro from VBA ................................................................................. 24
Objects The Grammar ........................................................................................... 25
Using Properties and Methods .................................................................................. 26
The Object Browser.................................................................................................. 27
The With Statement .................................................................................................. 29
Entering Text in the Current Cell .............................................................................. 30
Moving to Other Cells .............................................................................................. 31
Editing Specific Cells ............................................................................................... 32
Using the Immediate Window .................................................................................. 33
Formatting Cells ....................................................................................................... 35
3
Using Variables ........................................................................................................ 37
Constants.................................................................................................................. 39
Object Variables ....................................................................................................... 39
Decision Making with VBA ...................................... 43
The IF Statement ...................................................................................................... 43
The Select Case Statement........................................................................................ 44
Procedures, Functions and Parameters .................. 46
Functions.................................................................................................................. 46
Pass by Value (ByVal) and Pass by Reference (ByRef) ............................................ 47
Optional Arguments ................................................................................................. 49
Creating Custom Functions ...................................................................................... 50
Repeating Actions with a Loop ............................... 54
FOR NEXT LOOP ................................................................................................ 56
FOR EACH NEXT LOOP..................................................................................... 58
IN-BUILT Functions in VBA .................................... 61
The Message Box Function ...................................................................................... 61
The Input Box Function ............................................................................................ 65
Text Related VBA Functions .................................................................................... 68
Date and Time Related VBA Functions .................................................................... 70
Range Related VBA Functions ................................................................................. 71
Using Worksheet Functions in VBA ......................................................................... 73
Using the FORMULA Property for the Range .......................................................... 76
Arrays in VBA ......................................................... 77
Using LBound and UBound ..................................................................................... 78
Using ReDim and ReDim Preserve for Dynamic Arrays ........................................... 78
Assigning Range Values Directly To an Array and Vice Versa ................................. 79
Dynamic Arrays using Variants ................................................................................ 80
Using the Split Function to convert a string to arrays ................................................ 81
Using the Join Function to convert a 1 dimensional array to a string ......................... 82
Using Excels Features through VBA ....................... 82
The Sort Method ...................................................................................................... 82
The AutoFilter Method ............................................................................................. 86
4
The Text to Column Method .................................................................................... 88
The Advanced Filter Method .................................................................................... 92
5
Automation using Macros
No one wants to repeat the same task over and over again. Excel users
especially hate the drudgery of repetitive work like data entry and
formatting cell after cell after cell. Fortunately, Excel offers a serious
time-saving tool called macros - miniature programs that automatically
perform a series of steps within any workbook.
Macros
These examples are just the tip of the macro iceberg. When you create
a macro, you can use the full range of Excel's features. It's like having a
personal assistant, skilled in the ways of Excel, ready to carry out
whatever instructions you provide.
Write the macro by hand, using pure VBA code. This option isn't as
difficult as you may think, but it isn't easy either. The problem
6
isn't learning the syntax, or rules, of the VBA language (which are
fairly basic); it's learning how to find all the Excel features you
want to use. When you want to enter text in a cell, create a new
worksheet, or print a selection, you need to find the right Excel
object that can handle the job. Objects are programming tools
that let you get at features you need. If you want to write macro
code that spell checks your spreadsheet, you need to know the
name of the spell checker object.
Record the macro using the Excel macro recorder. You turn the
recorder on, and then go about your business, entering text,
navigating a worksheet, and selecting choices from Excel's ribbon.
While you work, Excel records each operation and translates it into
the corresponding VBA code. When you're finished, you can stop
the recorder, save the macro, and replay it to repeat all the
actions you just performed.
Macro Security
1. Very High
2. High
3. Medium
4. Low
7
While Very High does not allow any macros unless it is hard coded into
the system, High security allows macros only from Trusted sources. This
implies sources from Microsoft or its associates. To get a trusted Digital
certificate for each macro Microsoft is to be contacted.
Low level of security entertains all macros and does not intimate the
user. This is a potential risk. Any newly sent Excel file could contain
potentially harmful viruses.
Medium level security allows all macros but while opening the file it
clearly prompts the user whether to enable or disable macros. If the
Excel file is from an unknown party, the user could disable the macro. If
the file is known, then the user could enable the macros. This option is
then, by far the best option and we advocate the user to keep this
option while practicing macros and throughout all the initial stages.
8
macros from this source check box. From then on, Office will enable the
macros without showing a security warning for any future documents
containing macros signed by this trusted source.
A digital signature is the public certificate plus the value of the signed
data encrypted by a private key. The value is a number generated by a
cryptographic algorithm for any data that you want to sign. This
algorithm makes it nearly impossible to change the data without
changing the resulting value. So, by encrypting the value instead of the
data, a digital signature allows the end user to verify the data was not
changed.
http://msdn2.microsoft.com/en-us/library/ms537361.aspx
(http://msdn2.microsoft.com/en-us/library/ms537361.aspx)
A Certificate Authority can issue you a digital certificate for code signing
for a fee. The Certificate Authority will do an in-depth identification
check before issuing a digital certificate for signing code. Be sure to get
a digital certificate that can sign code with Microsoft Authenticode
(Verisign calls this Class 2 or 3; Thawte calls this Developer Certificates),
rather than one that can only sign e-mail. If you try to use a digital
certificate that is not authorized to sign code, Office will warn that the
digital certificate is not trustworthy.
You can create your own certificate for personal use or testing purposes
with the SelfCert.exe tool provided in Office. This unauthenticated
certificate will allow you to sign your own macros, and to trust this
digital certificate so that all macros you sign will not generate a security
warning. This type of certificate is not validated by a Certifying
Authority, therefore, other users will see a warning not to trust it.
9
that this is not an authenticated certificate, and therefore the certificate
cannot be from Microsoft.
If you do not see a program icon for Digital Signature for VBA Projects
in your Office folder, to install the tool, follow these steps:
1. Quit all Office programs. Click Start, point to Settings, and then
click Control Panel.
2. In Control Panel, double-click Add/Remove Programs.
3. On the Install/Uninstall tab, click to select Office product.
Locating SelfCert.exe
By default you can find Selfcert.exe in the following location;
C:\Program Files\Microsoft Office\Office <version number>
If it is not there run Office setup and choose a custom installation
and then advanced customization. Expand the Office Shared Features
Section and select Digital Certificate for VBA Projects to run from
your computer. For Office 2000 you can find this under the Office
Tools section.
10
As explained in the dialog a selfcert is for personal use only
11
Select the certificate you just created and click OK
In the main Excel Macro window choose Tools-> Macro-> Security and
make sure it is set to Warnings for signed macros; all unsigned macros
are disabled in Excel Macro 2007 and for any previous versions it reads
High. Only signed macros from trusted sources will be allowed to run.
Unsigned macros are automatically disabled.
Now that weve signed the code and verified that the security settings
are set correctly you must close Excel Macro. Youll get prompted if you
12
want to save changes to your VBA project. Choose Yes. Once Excel
Macro is fully closed start it again.
Now that were all set you can run the macro by Tools-> Macro->
Macros (ALT+F8). Since it is the first time that you are using the
certificate youll be prompted what to do. Select that youll always trust
the certificate from this publisher and youre then done! Now your own
macros will run without any security prompts and you can still enjoy
Excel Macro with your security settings on high.
The macro recorder is easy to use, but keeps a few key points in mind
while you're recording so that you end up with a great collection of
really useful tools:
13
Before you jump into the macro recording studio, it helps to understand
the difference between recording modes and to know where Excel saves
your macros. Those topics are covered in the next two sections.
When you click a command, Excel's macro recorder knows exactly what
you're doing. However, sometimes Excel needs a little guidance from
you in order to decide how to interpret some of your actions. When you
type in text, Excel can interpret your action in two different ways,
depending on which of two recording modes you're in:
14
If you used absolute reference mode, here's the series of instructions
that Excel stores in your macro:
1. Move to cell C1.
2. Enter the number 42.
On the other hand, if you used relative reference mode, Excel stores this
list of instructions:
1. Move two columns to the right (from wherever the active cell is).
2. Enter the number 42.
You'll see the difference if you clear the worksheet, move to cell E10,
and play the macro. If you used absolute reference mode when you
recorded the macro, then the macro always returns to cell C1 to enter
its information. If you used relative reference mode, Excel enters the
number 42 two cells to the right of the current cell, in cell G10.
Once you've crafted the perfect macro, you need to make sure Excel
stores it so that you can find it later on. In Excel, every macro's
attached to a workbook and saved in that file. When you open a
workbook that contains a set of macros, Excel makes them available
instantly.
Excel beginners often assume that before you can use a macro in a
particular workbook, you need to store the macro inside that workbook.
In fact, macros have a much greater range. As soon as you open a
workbook that contains any macros, Excel makes those macros available
to every other workbook that's currently open.
15
a hitch. Once you close MacroCollection.xls, those macros are no longer
available.
This design makes it easy to share and reuse macros across workbooks.
It is up to you whether you want to store macros in your most
commonly used workbooks or create standalone workbooks that hold
collections of useful macros. Companies evolve specific procedures for
macro storage and prefer separate macro workbooks.
When you record a macro, Excel gives you three slightly different
storage options:
It makes sense to save your most useful macros in your personal macro
workbook, so that they're always available, without requiring any extra
steps. Excel stores the personal macro workbook in a file called
Personal.xls, which lives in a folder named XLStart. You can find the
XLStart folder in a location inside the Microsoft folder. The XLStart folder
is usually right next to your templates folder.
Keep in mind that Excel doesn't actually create the personal macro
workbook until you add your first macro to it. So, unless you've
recorded at least one macro for the personal macro workbook to hold,
there's no point hunting for it.
Useful Tip: One useful place to put macros is in an Excel template. That
way, every time you or anyone else creates a new workbook based on
the template, you have immediate access to the macros. In order to put
16
macros in a template, record them inside the template using the
ThisWorkbook option.
Note that ThisWorkbook implies the Work Book in which the code
is written. To imply the macro for the current Work Book you need to
use ActiveWorkbook.
Using shortcut keys can be dangerous because Excel doesn't warn you if
you choose a shortcut key that correspond to another Excel task.
If this sort of conflict occurs, Excel always uses the shortcut key for the
macro. This habit can cause confusion if other people use your macros
and you replace a common shortcut key. Imagine their surprise when
they hit Ctrl+S to save a document and end up triggering a macro that
turns all negative numbers positive.
Here are some common key combinations that you should never assign
to macro shortcuts because people use them too frequently:
o Ctrl + S (Save)
o Ctrl + P (Print)
o Ctrl + O (Open)
o Ctrl + N (New)
o Ctrl + X (Exit)
o Ctrl + Z (Undo)
o Ctrl + Y (Redo/Repeat)
o Ctrl + C (Copy)
o Ctrl + X (Cut)
o Ctrl + V (Paste)
To avoid problems, always use Ctrl + Shift + letter macro key
combinations, because these combinations are much less common
than the Ctrl + letter shortcut keys. And if you're in doubt, don't
assign a shortcut key when you create a new, untested macro,
especially if you think it may conflict with an Excel shortcut key.
You can always assign one later if the macro proves extremely
useful.
Note1: The macro recorder stores code, not your specific actions. That
means it doesn't matter whether you activate a feature using a shortcut
key or the Quick Access toolbar or Menu. In all cases, the macro code is
the same.
17
Note2: If you get an error message informing you that Excel has turned
off the macros in your workbook (which it does automatically when you
close and reopen it), you need to take a few extra steps. Select Tools
Macros - Security and set it to medium. You then need to close and
reopen the file in question.
Note3: Once you play a macro, you're stuck with the changes. Sadly,
the Undo feature can't reverse a macro, so make sure you save your
worksheet before trying out an untested macro or on a crucial data.
Tip: If you created a shortcut key for your macro, you can trigger the
macro just by pressing the appropriate key combination, without using
the Macro dialog box. Also, you can attach a shortcut key to an already
created macro. Just select Tools Macros (Alt + F8). When the Macro
dialog appears, choose the corresponding macro and select options.
Then enter (or change) the shortcut key.
You'll find that you can record only actions that you can perform
yourself. If you want to create a macro that inserts a column with 100
identical cell values, you need to go through the drudgery of typing in
each cell value so that the macro recorder knows what to capture. A
more serious problem is that when you record a macro, you can respond
only to the worksheet that's in front of you. If you want to make a more
flexible macro that has the ability to examine a variety of cells and the
intelligence to respond to different conditions, you need to tap into some
of VBA and its advanced capabilities.
18
designed to edit the macros created for Office applications like Word and
Excel.
To show the Visual Basic editor window from inside Excel, press Alt +
F11 or choose Edit in the macro dialog window. When you do, Excel
launches the standalone window shown in Figure.
Figure-1: The Visual Basic editor window is divided into three main
regions: the Project window, the Properties window, and the Document
window. The Document window is where your code appears (it starts off
blank). The Project window lists all your projects (and the personal
macro workbook). The Properties window shows individual settings you
can change for the currently selected project.
Module Window
Project
Explorer Coding Area
Window
Property
Window
Immediate
Window
19
Workbook will be displayed, if they are open. Under each workbook,
there will be worksheets and Modules. This is as shown below:
This Workbook object and each of the worksheet objects are principal
Excel objects for Event handling. Properties for each of the worksheets,
workbook and each of the modules can be seen in the properties
window. Select any one of the Excel objects say, a worksheet in the
project Explorer window and press the F4 key to see the properties
window for that object:
Properties of the worksheet object are displayed here. Going back to the
project Explorer, if we double click on any of the modules, a code
window will appear showing the code details and is as shown:
20
This shows all the macros written in that module. On the top right drop
down you have the option of choosing the appropriate subroutine and
going directly to it.
Also, on the bottom of the editor, there may be a window called as the
immediate window. If this is not present it will be available in the View
Option or, by typing Ctrl + G. This window is aptly named. Any single
line VBA instructions can be given and the result in Excel is
instantaneous. This is used as a testing tool and any one time code can
be directly given in this area.
Modules contain macro code. Ordinarily, Excel creates a new module the
first time you record a macro, and names it Module1. Excel then places
every macro you record into that module. If you want, you can separate
macros into different modules for better organization. However, the
number of modules you create, or the module you use for a given
macro, has no effect on a macro's function.
21
Sub FirstMacro ()
Your macro code goes here.
End Sub
First, it shows you how to start and end any subroutine (by using the
statement's Sub and End Sub). Secondly, this code also shows you how
to create a comment. Comments are special statements that Excel
ignores completely; they're notes to you (like explaining in plain English
what the following or preceding line of code actually does). To create a
comment, you just place an apostrophe (') at the beginning of the line
or a rem word at the beginning of the line.
Following is the complete VBA code for the FormatRow macro. To make
it easier to analyze, each line of code has been numbered, and the code
has been simplified a little from what Excel generated automatically:
1 Sub FormatRow ()
2 '
3 ' FormatRow Macro
22
4 ' Macro recorded 4/6/2005 by R. Bhaarath
5 '
6 ' Keyboard Shortcut: Ctrl + Shift + F
7 '
8 ActiveCell.Rows.EntireRow.Select
9 Selection.Interior.ColorIndex = 35
10 Selection.Interior.Pattern = xlSolid
11 ActiveCell.Offset (2, 0).Select
12 End Sub
Line 1 starts the macro and defines its name. Lines 2-7 are simply
comments. They appear in green writing in the editor and don't actually
do anything (other than convey information to the person reading the
code).
The action gets started with line 8. Here, the code accesses a special
object called Active Cell, and uses it to select the entire current row.
Next, line 9 changes the background color of the selected cells (to light
green), and line 10 sets the type of background fill (to solid). Both of
these lines use the Selection object.
Finally, line 11 returns to the Active Cell object, and uses its Offset
command to jump down two rows from the current cell. Line 12 marks
the end of the macro code routine.
Altogether, this macro doesn't do much, but the code is quite dense,
and fairly difficult to read on first sight. The problem isn't the VBA
language. In fact, the only language-specific details in this example are
the Sub and End Sub statements (not to mention all those odd periods,
which are explained later on).
The real complexity comes from understanding all the different objects
that are available. To write a macro like this one, you need to know that
there's an Active-Cell object that lets you select rows and move from
row to row, and a Selection object that lets you adjust formatting. These
details make up Excel's object model. If you want to perform any task in
a macro, from printing a document to saving a worksheet, you need to
first figure out which object can do your bidding.
23
Running the Macro from VBA
The Macro can be directly run from VBA by pressing F5 or the Run
Button. Furthermore for purposes of analysis, the F8 button is very
useful as it will enable running Macros line by line. Further, you can
have toggle break points at any line of code while running the macro.
The macro stops at that line of code awaiting your approval to continue
running by pressing the F5 or F8 keys. This is as shown below:
24
Objects The Grammar
25
Using Properties and Methods
So how do you change properties or use methods? The answer is the
period. Imagine you have a Cell phone object that provides a Call
method. In this case, you use the following syntax to call:
Cellphone.Call
The same technique works with properties, but it tends to look a little
different. With properties, you typically want to perform one of two
actions. Either you want to retrieve information about the property, or
you want to change the property. To change the property value, you use
the equal sign (=). The following line of code changes the number of
people in a car by modifying the Passengers property:
Tip: Think of the equal sign as an arrow pointing to the left. It takes
whatever information's on the right side (in this case, the number 2)
and puts it into whatever is on the left side.
Car.Passengers = 2
Application.Workbooks refers to all workbooks currently open.
Workbooks.Item (1) refers to the first workbook and is usually
abbreviated to Workbooks (1)
A workbook (Sales.xls) refers to the workbook by name.
A workbook usually contains worksheets, each of which contains ranges
of cells. So, you might get cell B3 referred to as
Workbooks ("B1.xls").Worksheets ("Sht1").Range ("B3").Select
If you do not specify a particular workbook or worksheet, Visual Basic
will use the active workbook and the active worksheet. If that is
according to your wishes, then the long description above could be
reduced to just Range ("B3").Select as in the macro you recorded.
Each object has its own characteristics. In general, properties control
the appearance of objects. Thinking again about the Range object,
typical properties would be
Column Width Font
Formula Text
Value Offset
Objects have methods that perform actions on them. If you were
considering the Range object, then examples of methods would be:
Activate Cut
Clear Delete
Copy Select
26
The Object Browser
Excels VBA has several objects. These objects follow a hierarchy. This
hierarchy starts with the fundamental object called as the Application
object. All objects are sub objects to it. The Excel object Model is as
shown below:
27
Objects above can call objects below. The worksheet object can call the
range object using the dot (.) operator.
The Object Browser is a collection of all Excel and VBA objects and their
properties and methods that are present. When more references are
added, the scope of the object browser increases. On pressing the
Function Key F2, the object browser opens and is as shown below:
28
A=5: B = 10: C = A + B: MsgBox C
End Sub
In this example, two objects are at work. The Selection object contains
another object named Interior. Technically, Interior is a property of the
Selection object. Unfortunately, the Selection object doesn't give you
any way to change the background color of the selected cells.
To make life even more interesting, consider line 8, which has three
periods:
ActiveCell.Rows.EntireRow.Select
29
In this case, the ActiveCell object has a property called Rows, which is
also an object. The Rows object has a property named EntireRow, which
is yet another object. The EntireRow object is the one you want. It
provides the Select method that highlights the entire current row.
Colors can also be identified using the RGB property. Any custom color in
an application such as Paint displays the RGB colors. That particular color
can be incorporated into Excel using the R, G and B number codes. For
Example, to have a blue font we can write:
Selection.Font.Color = RGB (0, 0, 255)
To have a Yellow Background (Interior) we can write:
Selection.Interior.Color = RGB (255, 255, 0)
30
ActiveCell.Value = "My First Macro"
End Sub
With a little more effort, you can edit the current cell value instead of
replacing it with new content. Imagine you want to take the current text
value, and add the message "Note: " before the text. To accomplish this
feat, you can use the following macro code:
Sub RbsMacro ()
ActiveCell.Value = "Note: " & ActiveCell.Value
End Sub
In this macro, Excel begins by joining together two pieces of text: the
word "Note: " and whatever content's in the current cell. It then takes
that combined piece of text and places it back into the cell. In this
macro, the ampersand symbol (&) is key. It's a concatenation operator,
which means it glues together different pieces of text.
You can use a similar approach to adjust a cell that has a number in it.
In this case, you can use all the ordinary numeric operators, like +, /, *,
and ^. Here's an example that multiplies the current cell value by 2,
subtracts 1, and enters the new value:
Sub RbsMacro ()
ActiveCell.Value = (ActiveCell.Value * 2) - 1
End Sub
Note: When using arithmetic operators, make sure the current cell
contains a valid number. Otherwise, your code fails with a cryptic "type
mismatch" error, which is a reminder that Excel can't perform numeric
calculations with text.
31
Sub RbsMacro ()
'Change the top cell.
ActiveCell.Value = "Top cell"
Using Value and Offset, you can romp around your worksheet changing
cells as you please. The example macros you've seen so far use relative
references, which means they start working in the current position in
the worksheet. However, in some situations you want to move to a
specific cell. In order to do this in macro code, use the Range object.
The basic technique is easy. You supply the cell address (like A2) as an
argument to the Range object, and then use Activate or Select to
32
move to the cell. If you just want to change the cell, you can use the
Value property to alter its content without leaving your current position.
Here's an example that shows both techniques:
Sub RbsMacro ()
'Change cell A1.
Range ("A1").Value = "This is A1"
The Immediate window can be effectively used to test code. Type the
following details in the immediate window to see if the actions are
carried out in Excel:
Range ("A1:A10").Value = "Hello"
Range ("B1:D7, F8:J20").Select
Range ("C: C").Select
Range ("7:7") .Select
Range ("B: D").Select
ActiveCell.Value = "Note: " & ActiveCell.Value
33
To obtain values in the immediate window, the statements must be
preceded by a question mark (?). For example:
? Range (B:B).Count
? Range (2:2).Count
? ActiveCell.Value
Selection of special cells can be done in Excel. For example, to select only
cells containing formulae, we type:
Cells.SpecialCells (XlCellTypeFormulas).Select
For selecting formulas in a Range i.e. say some selected cells, we type:
Selection.SpecialCells (XlCellTypeFormulas).Select
With Selection
'Note that the alignment properties take special constant values.
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlBottom
.MergeCells = True
End With
35
to give 2 slashes. The first one prevents the second from behaving as a
format specifier.
The Indian system of accounting uses Rs as the currency symbol. Besides the
comma separator appears after every two numeral digits barring the thousandth
separator. For Example :
[>9999999]\R\s * #\,##\,##\,##0.00;
First Section: For Numbers above Ninety Nine Lakhs
\R\s * #,##0.00
Last Section: For other Numbers below One Lakh
36
Using Variables
Every programming language includes the concept of variables, which
are temporary storage containers where you can keep track of
important information. In an Excel macro, you can use variables to get
around problems that you just can't avoid with the macro recorder.
Imagine you want to swap the content in two cells. On the surface, this
operation seems fairly straightforward. All you need to do is copy the
text in one cell, place it in the other, and insert the other cell's text in
the first cell. Unfortunately, once you paste the new cell content into the
second cell, you end up overwriting the content you want to put in the
first cell. The easiest way around this problem is to use a variable to
keep track of the information you need.
To create a variable in VBA, use the oddly named Dim keyword (short
for dimension, which is programmer jargon for "create a new variable").
After the word Dim, you enter the name of the variable.
Here's how you'd create a variable named RB:
Dim RB
Once you've created the variable, you're free to put information in it and
take information out. To perform both these operations, use the familiar
equal sign, just as you would with properties.
Here's an example that stores some text in a variable:
RB = "Test this Text"
The following macro puts it all together. It uses a variable to swap the
content of two cells.
Sub SwapWithCellRight ()
'Create the variable you need.
Dim RB
'Copy the value from the cell on the right into the current cell.
ActiveCell.Value = ActiveCell.Offset (0, 1).Value
'Copy the value from the variable into the cell on the right
ActiveCell.Offset (0, 1).Value = RB
End Sub
The RB variable used above is called as a variant. A variant data type
can store Integers, Strings or any type of data. But it takes more
memory and is not specific. Specific data-types are available such as
Integer, Double, Single, String etc. To declare them we do it as shown:
Dim Rb1 as Integer
Dim Rb2 as String, Rb3 as String
Dim Rb4 as Double etc.
37
They can then be used as other normal variables but they can only store
that particular type of data. Different data types for variables are as
shown below:
Be wary of using the correct data type. Each data type has limits. For
instance we find that the integer variable can take value only between -
32767 and + 32767, failing which, a Data Overflow Error occurs. (Run
Time Error 6) Consider the following example:
Sub ErrorMacro ()
Dim n1 As Integer
n1 = 65536
MsgBox "The cell value is & n1
End Sub
The variable n1 is an integer that takes a value above 32767 causing an
error. But if n1 = 6653 only, you will find no runtime error.
Note: The MsgBox function is a message box function. Details of this are
explained under Built-in functions.
38
A variable declared in a procedure is local to that procedure and other
procedures cannot change its value. If you want other procedures only
in that module to have access to that variable, declare it at the top of
the module, before any Sub statements. The variable then becomes a
module level variable.
Constants
Values that dont change should be set up as constants rather than
variables. This prevents them being changed by accident.
The line:
Const pi = 3.14159
will create the constant pi that can then be used in an expression such
as
Rec = pi/2
(Note: VBA has several Built-in Constants such as VBOk, VBYes, etc.)
Object Variables
Note: The Range property of a range object indicates values within the
object. Supposing we have a list of cells say B6:G1055, the list contains
1050 rows and 6 columns. Suppose we set this range as an object:
Set Rng = Range(B6:G1055)
Then this list range is now Rng. To navigate within this list we can use the
Range property effectively:
Rng.Range(A1).Select will select the first cell in the Range Rng
namely, the cell B6.
Rng.Cells(1,6).Select will select the first row and sixth column of this
range Rng namely, the cell G6 will be selected.
To select an entire column or row, you could use the End property. The
End property of a Range object has the following arguments:
XlUp XlDown XlToRight XlToLeft
XlRight and XlLeft are alignment constants and should not be used here.
They should be used for formatting purposes for the Horizontal Alignment.
So the terminologies for the contants become XlToRight and XlToLeft
respectively.
In this case, to select the bottom of the cells use:
Rng.End (XlDown).Select or
Rng.Cells (Rng.Rows.Count,1).Select
To select the top right cell use:
Rng.End (XlToRight).Select or
Rng.Cells (1,Rng.Columns.Count).Select
To select the entire first column of the list use:
Range (Rng.Range (A1), Rng.End (XlDown)).Select
To select the entire First Column of the list use:
Range (Rng.Range (A1), Rng.End (XlToRight)).Select
To select the nearest full range rectangle (for lists) use:
Selection.CurrentRegion.Select
40
The Worksheet Object: The worksheet object, like the range object
has its own properties and methods such as add, delete etc. A few
examples are illustrated here for understanding worksheet objects
better: To add a new worksheet, use the following statements:
Sheets. Add or
Sheets. Add After: =ActiveSheet
The above statement will work fine except in early versions of Excel. The
following is the work around for adding a worksheet to the end of a
workbook:
Sheets. Add. Move After:=Sheets (Sheets. Count)
The following line of code will add a new sheet after the sheet name
"Result" and name the newly added sheet as "RB1"
Worksheets. Add(After:=Worksheets("Result")).Name = "RB1"
The following statement illustrates how to copy a sheet and at the same
time relocate the copy to the end of the workbook.
Sheets("My Sheet").Copy After :=Sheets(Sheets.Count)
If you wanted to copy it after a specific sheet, then you would put that
sheet's name in place of Sheets.Count. Please note that you do not have
to select the sheet in order to copy it.
The following line of code copies the sheet RB1 to a new workbook and
makes that workbook the active workbook:
Sheets("RB1").Copy
The following line of code copies the sheet RB1 to another workbook by
the name B1.xls after a specified worksheet, say sheet Sh1:
Sheets ("RB1").copy after:=workbooks("B1.xls").worksheets("Sh1")
In case, instead of copying the sheets to another location, the move
method can be used to literally move the sheets to another location. In
place of wherever the copy method is used, the move method needs to
be added.
Visible is a property of the worksheets and can take three values viz, -1
(visible), 0 (Hidden) or 2 (Very Hidden). Setting a value to be hidden
can be reset in Excel but if the value were to be set as very hidden, the
value can only be reset in VBA. For example:
Worksheets(RB1).visible = 2 - will set the sheet to very hidden
Worksheets(RB1).visible = 0 - will set the sheet to simply hidden
Worksheets(RB1).visible = 1 - will reset the sheet to visible
41
The WorkBook Object: Similar to the worksheet object, the
workbook object too has its own properties and methods. A few simple
examples for the workbook object is discussed in this section.
The simple way to open a file is with a statement like the following:
To save a workbook:
ActiveWorkbook.Save
To save the workbook in a different name:
Workbooks(RB1.xls). Saveas RB2.xls
To save and close a workbook:
ActiveWorkbook. Close SaveChanges: =True
To close a workbook without saving:
ActiveWorkbook. Close SaveChanges: =False
42
Decision Making with VBA
Conditional logic is another programming step, and it's code runs only if
a certain condition is true. There's no limit to the number of ways you
can use conditional logic. You could want to perform a different
calculation based on the value of a cell, apply different formatting based
on the number of cells, or create a different printout depending on the
date. All these operations and many more are possible when using
conditional logic.
All conditional logic starts with a condition, a simple expression that can
turn out to be true or false (programmers call this process evaluating to
true or false). Your code can then make a decision to execute different
logic depending on the outcome of the condition. To build a condition,
you need to compare a variable or property using a logical operator like
= (equal to), < (less than), > (greater than), and <> (not equal to).
ActiveCell.Value = 10 is a condition. It can be true (if the current cell
contains the number 10), or false (if the current cell contains something
else).
The IF Statement
On its own, a condition can't do anything. However, when used in
conjunction with other code, it can become tremendously powerful.
Once you've created a suitable condition, you can put it inside a special
structure called the If block. The If block evaluates a condition, and
runs a section of code if the condition is True. If the condition isn't True,
Excel completely ignores the code.
Here's a macro that looks at the current cell value. If that value exceeds
100, then Excel changes it to 100. If the cell value is less than 100,
nothing happens, and the current value remains.
Sub RbsMacro ()
If ActiveCell.Value > 100 Then
This value is too big. Change it to the maximum of 100.
ActiveCell.Value = 100
End If
End Sub
Note that the If block always starts with If followed by Then in the
same line and ends with End If. Everything else is conditional and runs
only if the condition is true.
The IF-Block is capable of evaluating several conditions. Here's an
example that considers the current value of a cell. Depending on the
cell's value, the If block uses a different calculation to arrive at the
sales commission, which it places in another cell.
43
Sub RbsMacro ()
If ActiveCell.Value > 1000 Then
Use the 5% commission rate.
ActiveCell.Offset (0, 1).Value = ActiveCell.Value * 0.05
ElseIf ActiveCell.Value > 500 Then
Use the 2.5% commission rate.
ActiveCell.Offset (0, 1).Value = ActiveCell.Value * 0.025
Else
Give a basic $5 commission.
ActiveCell.Offset (0, 1).Value = 5
End If
End Sub
Here, only one segment of code runs. Excel works its way through the If
block, testing each condition until one matches. If the cell value is
greater than 1,000, it runs the first conditional block of code, and then
jumps down to the closing End If statement.
If the cell value is less than 1,000 but greater than 500, the first
condition is false, and Excel tries the second option. This is given by the
ElseIf clause. This clause statement must also end with a Then. If both
the condition does not match, Excel runs the code in the final Else
clause. These examples scratch only the surface of what careful
conditional logic can do. You can use And and Or keywords to
combine conditions, put one conditional block inside another, and much
more. For Example, to check the largest of three numbers, the following
code is written:
Sub Largest ()
Dim A as Integer, B as Integer, C as Integer
A = 10
B = 20
C = 30
If A>=B And A>=C Then
MsgBox The Largest is: & A
ElseIf B>=A And B>=C Then
MsgBox The Largest is: & B
Else
MsgBox The Largest is: & C
End If
End Sub
44
Sub Vote ()
Dim I As Integer
I = InputBox ("Provide your age", "Age")
Select Case I
Case Is < 20
MsgBox "You aren't qualified to vote"
Case Is <= 60
MsgBox "You are so busy that you don't have time to vote"
Case Else
MsgBox "You are retired but too tired to vote"
End Select
End Sub
Select Case I implies that the computer selects from one of the many
cases depending on the value of I. If the first two cases are not
selected, the option used is Case Else. After executing code the
procedure ends provided we give the End Select statement.
The Case option could also use specific values Example: Case A More
than one value can also be checked. In the example given below, a
select case procedure is written based on the active cells value being A,
B, C, D or E:
Sub RBsMacro ()
Select Case ActiveCell.Value
Case "A", "B", "C"
ActiveCell.Offset (0, 1).value = First Three
MsgBox Excellent
Case "D", "E"
ActiveCell.Offset (0, 1).value = Next Two
MsgBox Good
Case Else
ActiveCell.Offset (0, 1).value = Last set
MsgBox Can Improve
End Select
End Sub
If the values are always in sequence, with no gaps you can write
Case "A" To "C"
As can be seen, multiple statements to be executed can be placed
between the Case tests.
45
Procedures, Functions and Parameters
Generally one macro procedure can call another procedure either within
the same module or outside of it. Calling is done by simply mentioning
the macro name. Consider the Example below:
Sub RBTest ()
Dim A as Integer, B as Integer, C as Integer
A = 10
B = 20
C = 30
RBMacro
End Sub
Sub RBMacro ()
MsgBox Good to have you study this
End Sub
What happens when the first Macro RBTest is executed? It simply calls
the macro RBMacro and the Message in RBMacro is displayed. A
Subroutine can also take arguments. The same Macro above can be
edited as shown:
Sub RBTest ()
Dim A as Integer, B as Integer, C as Integer
A = 10
B = 20
C = 30
RBMacro (A, B, C)
End Sub
Note: What if you have the same Macro Name in two different
Modules. Then, to call a specific macro, one needs to include the Module
Name as well. This is how that is done:
Call Module1.Macro3 (The call is optional but advisable)
Functions
In this case the sum is also displayed. But a subroutine merely can be
used to display a Message Box. It cannot be used to return any values.
46
Instead of a subroutine for RBMacro, it is better to have a Function. In a
Function, values can be returned. In this example, the original
Subroutine RBMacro can be given as shown:
Note: Since calculation is carried from right to left, the values N1, N2
and N3 will be added first.
Sub RBTest ()
Dim A as Integer, B as Integer, C as Integer, RES as Integer
A = 10
B = 20
C = 30
RES = RBMacro (A, B, C)
MsgBox The sum is & RES
End Sub
In a function, the name of the function itself is the variable that will
return the result of the Function. In the above function the sum of the
variables are returned to the variable RES.
The Functions RBMacro has three arguments passed into it. By default
the arguments passed are by reference only. But they can also be
passed by Value.
If you see the example above, the Function RbsMacro takes these
arguments as N1, N2 and N3 respectively. Actually these values N1, N2
and N3 refer to the same variables A, B and C. So, when we pass
47
arguments by Reference or by default, Changing the values N1,
N2 or N3 changes the values A, B or C.
To illustrate the statements above let us further edit our macro RBTest
and this time, we shall have two different types of functions:
Sub RBTest ()
Dim A as Integer, B as Integer, C as Integer
Dim RESByVal%, RESByRef%
Using % implies that you dimension as Integer
A = 10
B = 20
C = 30
'Call by Value
RESByVal = RBByVal (A, B, C)
Displaying values of A, B and C to see if they are still 10, 20 and 30.
MsgBox "Result val of & A & "," & B & "," & C & "is" & RESByVal
'Call by Reference
RESByRef = RBByRef (A, B, C)
Optional Arguments
Optional Arguments are arguments which need not be passed in a
function. Even if you have seen Excel Functions, optional arguments are
present and appear in the yellow palette in square brackets. Even in
VBA when a user made function has an optional arguments, it will
appear in Square brackets in the yellow palette. To use an Optional
argument in function a typical example is as shown:
Function RBsFunction (n as Single, n1 as String, Optional n3 as String)
Sub RBTest ()
Dim A as Integer, B as Integer, C as Integer
Dim RES1%, RES2%
Using % implies that you dimension as Integer
A = 10
B = 20
C = 30
RES1 = RB (A, B, C)
MsgBox "Total result of" & A & "," & B & "," & C & "is" & RES1
RES2 = RB ( A, B )
MsgBox "Optional result of" & A & "," & B & "," & C & "is" & RES2
End Sub
49
Creating Custom Functions
So far, you've seen how you can use code to create powerful macros
that take control of Excel. But you have another option for plugging your
logic into Excel: You can create custom functions (user-defined
functions). Essentially, a custom function accepts some information
(through arguments), performs a calculation, and then provides a result.
Once you've created your custom function, you can use it in a formula in
a cell, in exactly the same way that you use Excel's built-in functions.
You create custom functions in the same place that you create macros in
modules. In fact, a number of macros and functions can exist side-by-
side in a module.
Here's an example of one of the simplest possible custom functions:
Function Name ()
Name = ThisWorkbook.Name
End Function
The above function Name will be available in functions in Excel under
User Defined functions after you enter the above function in a module.
Note that the Function should not be declared Private. By default, it is
public and so the keyword can be safely omitted.
Every function needs to provide a result, which is what appears in the
cell when you use the function. To set the result, you use the name of
the function, followed by an equal sign and the value, as shown here:
GetName = ThisWorkbook.Name
The file name of the active Workbook is allocated to the function name
in the above statement. This then, is the result of the function. To use
the function in your worksheet, just create a formula that uses the
function.
The GetName ( ) function is particularly simple because it doesn't use
any arguments. But arguments can be used just like normal functions.
Consider the following custom function, which takes two arguments
length and width and calculates the total area by multiplying them
together:
Function Area (Length, Width)
Area = Length * Width
End Function
Now, to use this function in a cell in your worksheet, you can type this
formula:
=Area (100, 50)
50
Consider the example below where in the Tax is calculated for different
income groups. This is based on the Tax structure in India during 2007-
08. Surcharge has not been included for those who are very specific:
Else
'Normal Category - No Concessions
If Amt <= 110000 Then
Tax = 0
ElseIf Amt <= 150000 Then
Tax = 0.1 * (Amt - 110000)
ElseIf Amt <= 250000 Then
Tax = 4000 + 0.2 * (Amt - 150000)
Else
Tax = 4000 + 20000 + 0.3 * (Amt - 250000)
End If
End If
End Function
The Function uses Tax slabs for Normal people, Women and seniors.
51
There are various tax slabs at 10%, 20% and 30%. For a normal citizen
there is no tax for salaries up to 1.1 Lakh. Then on, salaries above 1.1
Lakh would get 10% Tax slab. Salaries above 1.5 Lakhs would incur a
20% tax slab while that part of the the salary above 2.5 Lakhs would
incur a tax slab of 30%. The situations are slightly different for Women
and senior citizens.
You could then try the Tax function out in Excel to get the desired
results. Remember that Age and Gender are just optional values
VBA Tip1: When you try the above function, you will find that there
is neither help nor any description available. Do you want the Function
to have a description?
Open the Macro Dialog Box in Excel under Tools (Use Alt + F8). Type
the name of the custom function under the Macro Name area. Select the
options tab (You could also set shortcuts this way but that is for
Subroutines and has no relation with Functions). In the description, type
the description as to what the function will do. Close the macros dialog
box. Now open the function from the menu ans see the description.
VBA Tip 2: The Function you have created appears in the User
Defined Section only. This is because they fall by default into the UDF
(User Defined Function) category. Can this be changed? The answer is
YES.
Excel does not provide a direct way to assign a custom function to a
category. The only way is to execute a line of VBA Code. This can be
done in the immediate window or, inside a subroutine. The statement
below however, needs to be executed only once. Every time the
workbook is re-opened, the function will continue to appear in the
specified category unless it is re-allocated otherwise. The line of code is:
Application.MacroOptions Macro: =Tax, Category:=1
The category 1 refers to the Financial Category. The list of category
values is as provided below:
Number Category Name
1 Financial
2 Date & Time
3 Math & Trigonometry
4 Statistical
5 Lookup & Reference
6 Database
7 Text
8 Logical
9 Information
52
* Note: A Function need not return a value. When no return value is
there, call the function without brackets. But when a return value is
taken, use brackets. This applies for all Built-In functions like Message
Box and Input Box etc.
VBA Tip 3: Some Excel functions are static while others are volatile. As
you may be aware the Rand (), RandBetween () and Now () functions are
volatile. They keep recalculating whenever any cell is recalculated or when
we press the F9 Key for recalculation.
Custom Functions are however, static by nature. Whenever any value is
entered in another cell, they do not recalculate. They recalculate only when
total recalculation is done (Ctrl + Alt + F9).
Let us write a function to calculate the random number between two values
(effectively the RandBetween () function). But you can incorporate this
function in Excel and compare it with RandBetween to see if it is volatile. The
function below incorporates two Excel Built-in functions Rnd () Similar to
Excels Rand () function and Int () which, is similar to Excel.
Public Function Random (High As Long, Optional Low As Long)
If IsMissing (Low) Then Low = 1
Random = Low + Int ((High - Low) * Rnd ())
End Function
There are two differences here.
1. Unlike RandBetween, you would be specifying the higher value first
and then the lower value (which is 1 by feault and can be omitted).
2. While RandBetween is Volatile, this function is not. Typing a value in
any other cell or pressing F9 will show you the change between the
two. To evoke a change in the Random () function you need to press
Ctrl + Alt + F9 .
For some instances, however, like time changes you may actually want to
have volatility for the function. To make a function as volatile, you may
need to use the following Application property:
Application.Volatile True
A volatile Random function would then be as shown:
Public Function Random (High As Long, Optional Low As Long)
If IsMissing (Low) Then Low = 1
Random = Low + Int ((High - Low) * Rnd ())
Application.Volatile True
End Function
53
Note: When we call a function with arguments, the arguments are
normally called in the exact order separated by commas. But if we need
to give it out of place, we could use the := operator. In a message box
the title option comes thirs and prompt, first. We can write as:
MsgBox Title:=Heading, Prompt:=Hello There
The loop is one of the best tools for repeating operations. A loop is
another type of block, one that repeats itself over and over again.
Here's an example:
Do
Selects the current Active Cell
ActiveCell.Select
54
3. Do Loop While (Condition is True)
4. Do Loop Until (Condition becomes True)
What this implies is that even if the Looping Condition is such that entry
into the Loop is not allowed, the statements in the Loop in the Third and
Fourth cases would be executed at least once. Here is a loop example
that stops as soon as the active cell is empty:
Sub AddBoldValue ()
Dim Sum as Double
Dim Str as String
Dim Rng as Range
Loop Starts
Do
Checking for the Font
If ActiveCell.Font.Bold = True Then
Sum keeps adding the cell value to itself
Sum = Sum + ActiveCell.Value
End If
Moves to the Next Cell
Activecell.Offset (1, 0).Select
Loops Exit Condition
Loop While ActiveCell.Value <>
The value of sum is put in the cell 2 cells below the last cell
ActiveCell.Offset (1, 0).Value = Sum
End Sub
55
FOR NEXT LOOP
Apart from the Do Loops, Excels VBA has a powerful For Next
Loop. This loop is used when looping has to be done a specific number
of times or until a value would increment itself up to a specific limit.
Sub RBSheetCount ()
Dim No as Integer, Counter as Integer
For Counter = 1 To No
MsgBox WorkSheets (Counter).Name
Next Counter
End Sub
In the above program, the variable Counter first takes the value of 1.
The Message Box displays the name of the first Worksheet. Then
Counter becomes 2 and so on until the Counter finally reaches the value
No which, is the number of worksheets. This will be that last time the
Loop runs. After this the Loop exits and the statement(s) after the Loop
is executed. One Loop can be nested inside another. Consider the
following Loop Example:
Sub RBLoop ()
Dim i As Integer, j As Integer, ctr As Integer
'Work on a new sheet
i=0
ctr = 0
Do While i < 10
i=i+1
'i is the row and keeps increasing
For j = 1 To i Step 1
'For each value of i, j is the column and j keeps increasing
'The value of i is printed in all the columns using cells (row, column) object
Cells (i, j).Value = i
56
'ctr counts the number of times the inner loop is carried out
ctr = ctr + 1
Next j
Loop
MsgBox "loops & ctr & times."
End Sub
Let us work one more example on a nested loop. This time we will nest
one for loop inside another for loop. Remember we carried out the Add
bold values to a single column of cells. This time we will carry out a
similar functionality but this time, it is not going to be just one column.
We will request the user to give the range address and using this
address we will carry out the same procedure. We will have two
variables Row and Col which represent the number of rows and columns
for the range. The variables RR and CC will be the row and column
counters respectively. Now, on to the procedure:
Sub RBSumBold ()
Dim Sum as Double
Dim STR as String
Dim Rng as Range
Dim Row%, Col%, RR%, CC%
Sum = 0
STR = InputBox (Provide Range Address. Example: A6:G50)
Set Rng = Range (STR)
For RR = 1 To Row
For CC = 1 To Col
If Rng.Cells (RR, CC).Font.Bold = True Then
Sum = Sum + Rng.Cells (RR, CC).Value
End If
Next CC
Next RR
MsgBox The Sum of Bold Values is: & Sum
End Sub
57
FOR EACH NEXT LOOP
While the conventional For Next Loop is used for Data type Variables
such as Integers, Double, String or Variant, the For Each Next loop is
exclusively used for objects in a collection. In a work book,
WorkSheets is a collection which has several WorkSheet objects. A
Range contains a Cells collection which is a collection of Cell objects.
This Loop is a very useful Loop to traverse through each and every
object in any given collection. Visual Basic itself figures out the number
of times the loop should execute. The syntax is as shown:
Let us now try out an example to do the same thing as last time, i.e. to
sum the Bold values. The reason we are first trying out the same
example is to illustrate the ease with which a For Each Next Loop can
be done Example - 1.
Sub RBSumBold ()
Dim Sum as Double
Dim STR as String
Dim Rng as Range, Cl as Range
Sum = 0
STR = InputBox (Provide Range Address. Example: A6:G50 )
Set Rng = Range (STR)
58
Flag = 0
Na = InputBox (Provide the Sheet Name, Sheet)
For Each ws in Worksheets
If ws.Name =Na Then
Flag = 1
End If
Next ws
If Flag = 1 Then
MsgBox Sheet Exists
Else
MsgBox Sheet Missing
End If
End Sub
Flag values are often set in good programs as Indicators.
Tip: In the last example which was done, there may have been 10
worksheets. The name might have matched in the first instance of the
loop itself and the flag would have been set to 1. But still, until all the
sheets are checked the loop progresses. This is a waste of time and
memory for the computer.
For this, Visual Basic has two Exit statements. These are:
In th above Example, after the Flag =1 statement is set and before the
End If Statement we need to introduce a line as shown:
Exit For
This will stop the loop and VBA will proceed to the line of code after the
Loop.
Sometimes for a condition we may need to exit from the macro itself.
We the need to use:
Exit Sub
To Exit from a Function instead of a Subroutine, we need to use:
Exit Function
59
Tip: In the example before, we were trying to see if a sheet exists.
Suppose we wanted to delete the sheet, we would have written:
Ws.Delete where Ws is the Worksheets object that points to the worksheet.
But whenever a sheet is deleted the system will generate a prompt. It is
sometimes undesirable when we need to automate the process. We can
switch off and on alerts before and after the delete statement as shown:
Application.DisplayAlerts = False
Ws.Delete
Application.DisplayAlerts = True
This will ensure that prompts and alerts do not occur during deletion.
60
IN-BUILT Functions in VBA
Just like Excel VBA has got several Built-In Functions in it. For example,
the built-in function UCase is similar to Excels Upper Function in
converting the string to Upper case. Some of the ones used by you till
now are MsgBox, InputBox, and IsMissing etc. Some of the most
common functions will be discussed here starting from the Message Box
Function.
This function is one of the most widely used functions in VBA. This is
also an excellent debugging tool because one can insert it at any point
in the code to halt your code and display a required variable value. Like
every function this function also returns a value.
61
Type Option Value Description
vbCritical 16 Display Critical Message icons.
vbQuestion 32 Display Warning Query icon.
vbExclamation 48 Display Warning Message icon.
vbInformation 64 Display Information Message icons.
Either the option or the value can be typed. For Example:
MsgBox RBs Macro session is boring, 3,Choice OR
MsgBox RBs Macro session is boring, vbYesNoCancel, Choice
If you combine this with the type value option, say vbQuestion then the
combined value is 32 + 3 = 35. We then write:
MsgBox RBs Macro session is boring, 35,Choice
The result will look as shown:
The dafault selection will usually always be the first button. Here are the
values for the other defaults. These values must be added to get the
right touch:
Default Value Description
vbDefaultButton1 0 Default.
vbDefaultButton2 256 Second button
vbDefaultButton3 512 Third button
vbDefaultButton4 768 Fourth button
Let us now try and add these values to choose. Let us say we want to
give Information. So our Type Option is Information whose value is 64
62
We want vbYesNoCancel whose value is 3
We want No to be our default. This is the second button. For this the
value for DefaultButton2 is 256
Our Total Value then is 256 + 64 + 3 = 323
MsgBox RBs Macro session is boring, 323,Choice
The second button is default in this Information type Message. This way,
my session will not be boring by default !
Also, in the above case the message box actually gives us an option to
say yes, no or cancel. To exercise this option we must have the
message box return a value. Whenever the function returns a value,
brackets must be used. The values returned are based on which button
we click. Consider this statement:
K = MsgBox (RBs Macro session is boring, 3,Choice)
If K is 6 then you must have clicked yes. Here is an index of what values
will be returned upon clicking the desired button option.
Constant Value
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7
Example:
Sub Choose ()
K = MsgBox (RBs Macro session is boring, 3,Choice)
If K = 6 Then
MsgBox You clicked yes
Elseif K = 7 Then
63
MsgBox You Clicked No
Else
MsgBox You clicked cancel
End If
End Sub
While all of them work in a Message Box, a userform entry works best
with both Carriage Return and Line Feed ( i.e. vbCrLf only). It would be
advisable to use vbCrLf for all cases.
The above Message Box will appear as shown. Notice the exclamatory
Message Box with the default button being the third button:
64
The Input Box Function
If the user terminates the dialog with CANCEL, then the function returns
an empty string.
Default This is the default value that appears where the user has to
input data. If omitted the user input area is blank.
Xpos & Ypos The position of the Input Box window relative to the top
left hand corner of the application in units called as Twips. If omitted, it
will be horizontally centered and vertically placed at one-third the
distance from the top. Generally this position is widely accepted and
providing values are omitted.
Help File and Context Files are also optional and are similar to those in
Message Box statements.
65
If the value 20 (the default value) is omitted, the user input area will be
blank. If the Tile Age is omitted the default title will be Microsoft
Excel. The value obtained is usually a string but numbers are
automatically returned to number variables (Conversion is not required).
The normal Input Box function can only return variables. How about
returning a Range of cells? Yes. This is done using the Input Box method.
This is a special method invoked from the application object. (The only
alternative to accepting cell ranges is a user form). How does it work? The
syntax is shown below:
Application.InputBox
If Type = 1 + 2 we can accept both a number and a text. But only the
type given is specifically accepted. Type-8 accepts Ranges and Type-16
accepts arrays.
66
VBA Tip 2: Input Box Method Types 8 and 64
for Range / Arrays
There are four array elements the user has entered in this case.
67
Text Related VBA Functions
Visual Basic has several Text related functions which will be discussed:
1. UCase and LCase: Converts Text to upper cae and lower case
respectively. For example,
Example:
I4 = InStrRev (Serendipity, e) => I4 will be 4
I5 = InStrRev (Serendipity, I, 1) I5 = 9
As you can see, InStr locates the first available string from the
beginning while InStrRev locates the first available string from the
reverse direction.
3. Left, Right and Mid: These are similar to Excels functions but the
number of characters is not optional in this case. While the
function Left (Who) is W in Excel, it will generate an error in
VBA. It should be Left (Who, 1). Some Examples:
If StrComp returns
string1 is less than string2 -1
string1 is equal to string2 0
string1 is greater than string2 1
Example K = StrComp (rb,RB) => K=1
K = StrComp (rb,rb) => K=0
K = StrComp (a,b) => K = -1
69
Str6 = StrReverse (R.Bhaarath) => Str6 = htaraahB.R
2 Day: This function gives the day number for a given date. For
example: Day (#5/5/2007#) will return the day number i.e. 5.
3 Month: This function gives the month number for a given date.
For example: Month (#5/5/2007#) will return the month number
i.e. 5.
7 Year: This function gives the Year for a given date. For
example: Year (#5/5/2007#) will return the year 2007. Note that
VBAs calendar is only from 1/1/1900 and dates prior to that will
only yield an error.
70
9 DateSerial: If we have the year value, month value and day
values separately, how do we form a date in VBA? The answer is
the DateSerial. This function is simple and the syntax is as shown:
DateSerial (Year, Month, Day). This will return the date.
11 Hour: This function gives the Hour based on the time. For
Example: Hour (Now ()) provides the current hour.
12 Minute: This function gives the Minutes based on the time. For
Example: Minute (Now ()) provides the current minutes.
13 Second: This function gives the Seconds based on the time. For
Example: Second (Now ()) provides the current seconds.
Sub Waiter ()
Dim HR%, MN%, SC%
HR = Hour (Now ())
MN = Minute (Now ())
SC = Second (Now ())
Application. Wait (TimeSerial (HR, MN, SC +5)
Application waits for 5 seconds from now.
MsgBox Waited 5 Seconds
End sub
1 Union: This function returns the Union of two ranges. This is quite
useful in many situations. Assume there is an existing range -
variable RBRange which refers to a range of cells. We need to find
if the selected cells are within this range or not. Consider the
71
example given below. This is not a full procedure. If it is not a full
procedure from sub to end sub, it is usually called as a code
snippet:
Note that the union example assumes that the selection is smaller
than the given range. It does not go to check if the given range is
within the selection. If we logically combine both of these
functions, it is easy to establish if any relationship between two
ranges exists or not.
and will return a TRUE if the cell is empty and FALSE if the cell has
any value.
72
4 Using the DIR function
This function gives the name of the workbook for the full path. For
example if there is a file d:\example.xls, then
= LARGE (A1:B10,3)
The variable K will then contain the third largest value in the
Range A1:B10. Similar to large, many other functions such as
Max, Min, VLookup, Index, Match, SumIf, Countif etc. can be used
through the application object.
73
A Simple Case Study
Year Chennai Bangalore Hyderabad Mysore Bombay Goa Poona Delhi Calcutta
1991 R8506 R2465 R1808 R2508 R4664 R3106 R3215 R8218 R7201
1992 R8113 R6472 R3182 R7162 R7508 R1601 R9573 R9626 R7699
1993 R8861 R2203 R6133 R2251 R8416 R4784 R8956 R5299 R1682
1994 R4742 R3785 R5924 R4848 R8504 R7789 R8883 R8830 R1944
1995 R2466 R8796 R6057 R5036 R8759 R5173 R4530 R6949 R2763
1996 R4914 R8303 R7567 R5780 R1955 R6782 R1822 R4566 R1235
1997 R9511 R8559 R6068 R5236 R1721 R9370 R6392 R2828 R5281
1998 R6450 R5890 R1173 R9145 R2706 R7441 R3801 R5256 R5970
1999 R8790 R7838 R2375 R6831 R9748 R3743 R1278 R7737 R9727
2000 R5017 R6843 R4967 R2563 R3675 R5591 R8447 R5708 R8230
2001 R8300 R4017 R9634 R6841 R3179 R4382 R5674 R5488 R9771
2002 R8983 R5210 R2118 R6529 R9627 R3402 R4372 R1074 R5048
2003 R9782 R5039 R7198 R8763 R7947 R6383 R3895 R6338 R4631
2004 R4717 R6689 R1092 R1444 R3332 R1913 R6364 R7087 R6412
2005 R1138 R1205 R2052 R6349 R8167 R7080 R5530 R2249 R4891
2006 R2430 R2289 R8617 R7155 R3172 R2301 R4012 R4727 R4204
2007 R3342 R4284 R1635 R3270 R7620 R3101 R2834 R9931 R9181
2008 R9259 R3744 R3917 R9914 R2649 R9245 R4129 R5935 R4249
2009 R2617 R1893 R9988 R7490 R9833 R3816 R4477 R2949 R2241
When in excel, we call the function from the list of UDFs (User
Defined Functions), the following screen appears:
75
The rsulting data on usage of the UDF is as shown:
Security Values
Access
Code City Yr
R9573 Poona 1992
R1444 Mysore 2004
R5210 Bangalore 2002
R8416 Bombay 1993
R1601 Goa 1992
R3331 Bombay FALSE
R3342 Chennai 2007
R3917 Hyderabad 2008
The syntax is very simple. To find the sum for example, you use
Range(C4).Formula = =sum(A1:C3)
In this case, in cell C4, the formula will be writtern. This can be
used for all cases. Consider a vlookup example given below:
Sub lokup()
End Sub
In the above example, the cell G4 will have the necessary lookup
formula. Notice the lookup table range tb cannot be given as it is
in the formula property. Everything in the formula property must
76
be a text. As such, tb.address is provided and the texts are
concatenated to get the desired result.
Range(D4).FormulaR1C1==R[0]C[-2] + R[0]C[-1]
Here the formula in Cell D4 will be equal to the sum of the values
in the cells to the left of D4. When executed, the formula that will
be writtern in the cell D4 is =B4 + C4
Arrays in VBA
Arrays contain a sequence of variables. Each one is called an element of
the array and is identified by an index number.
Example 1
Dim cities (1 to 50) As String
Example 2
Dim htge (1 to 80, 1 to 80) As Single
Example 3
Also, the function called Array can create an array from a list of
variables as in
Children = Array ("Raju", "Leela", "Kripa")
When the Array function is used, the variables are of type Variant. This
in effect means that the variable Children should be dimensioned as a
variant.
77
Typically the first variable of a dimensioned array is array(0). This is by
default in cases where we dimension arrays. But this is not always the
case. When you use functions to generate arrays such as the Array
function above, then the first array would in most likelihood be Array(1).
In order to avoid such confusions, it is recommended to have all arrays
to typically start with array(1). To ensure this is done, we need to
declare the following statement on the top of the module:
Option Base 1
This statement ensures that all arrays by default will start from array
(1).
LBound and UBound are functions of VBA that are used to determine the
boundaries of the array. While LBound shows the Lower Boundary,
UBound shows the upper limit of the array. Consider an array:
City (3 to 9)
UBound (City) is 9
LBound (City) is 3
The arrays discussed earlier were static i.e. the size of the array was
fixed while dimensioning it. The size is not determined when the
program is running or at runtime. If that is the case then , the array is
considered to be dynamic.
If the size needs to be increased further, using ReDim will yield the
desired result but only at the cost of the array losing all its existing
data. For preserving the data one needs to use the ReDim Preserve
keyword to accomplish this task. Consider the example below:
Sub RBarr1 ( )
Dim i%, j%, k%
The Original dimensioning has no limits in a dynamic array as below
Dim arr ( ) As Integer
78
The array is re-dimensioned at run time i.e. when the macro runs.
ReDim arr(1 To j)
Obtaining Values for the array
For i = 1 To j : arr(i) = InputBox("Value", "Val") : Next i
k = InputBox ("How many more values:", "Values")
The array is re-dimensioned by preserving the existing values
If Preserve is not used the original values get deleted.
ReDim Preserve arr (1 To j + k)
For i = 1 To l: arr (j + i) = InputBox ("Value") : Next i
Lbound Lower boundary of the array In this case 1
Ubound Upper Boundary In This case j+1
MsgBox arr (LBound (arr)): MsgBox arr (UBound (arr))
End Sub
Sub WriteToAnArray ()
Dim myArray As Variant, n As Integer, m As Integer
'Assign range values to the variant variable
MyArray = WorkSheets (1).Range ("a1:c5")
'Determine the array size display in a message
Since the range is 2-dimensional, the array becomes 2-dimensional
Array size for a 2-dimensional array has to be given as below
n = UBound (MyArray, 1)
m = UBound (MyArray, 2)
MsgBox n & " " & m
'Display some values in the range
MsgBox MyArray (1, 1)
MsgBox MyArray (5, 3)
End Sub
Option Base 1
Sub arraytorange ()
Dim arr (5, 5) As Integer
79
Dim i%, j%, k%
Dim rg As Range
k=0
For i = 1 To 5
For j = 1 To 5
k=k+1
arr (i, j) = k The array arr gets values from 1 to 25
Next j
Next i
Set rg = Range ("D1:H5") rg has the same dimension 5 by 5
rg = arr We are assigning an array to a range directly
End Sub
If the above example is run, the range D1:H5 will get values of the
array arr viz. values 1 to 25.
Any variable that has been initialized as a variant can be converted into
an array while the macro runs. However, the initialization must be in the
form of a parametric array.
N = Array (Hello,How,Are,You)
Option Base 1
Sub vart ()
Dim Ready As Variant
Dim i%
Ready = Array (4, 5, 6, 7)
For i = 1 To UBound (Ready)
ActiveCell.Offset (i - 1, 0).Value = Ready (i)
Next i
End Sub
80
Using the Split Function to convert a string to arrays
The split function splits a string into several pieces based on a given
separator/delimiter. The split string is fed back as a parameter array
which can be caught by a variant. The syntax is:
Sub splitter ()
Dim txt$, dl$
Dim vr As Variant
Dim i%, lb%, ub%
'Obtaining text and delimiter
txt = InputBox("Give string to be split", "Input String")
dl = InputBox("Provide the delimiter", "Delimiter")
'Converting variant into an array
vr = Split (txt, dl) 'split results in a parameter array
lb = LBound (vr): ub = UBound (vr)
For i = lb To ub
ActiveCell.Offset (i, 0).Value = vr(i)
Next i
End Sub
When the delimiter is asked, we type ,. The text is then split and
written in the active sheet starting from the active cell.
The variant variable vr becomes an array that contains the split values
of the text.
81
Using the Join Function to convert a 1 dimensional array to a string
Sub joiner ()
Dim ABC$
Dim var1 As Variant
var1 = Array ("Ram", "Ravi", "Bhaarath", "Gopal", "Sundar", "Veera")
ABC = Join (var1, ",")
MsgBox ABC
End Sub
All the members of the array var1 are joined by the comma(,) delimiter
as specified in the join function used in the example above. The result
would be a message box as shown:
The sort method can be invoked from the range object using the
Range.sort option.
82
Parameters
Name Requirement Data Type Description
83
This list contains 3 fields. The user can choose any one field and sort the
entire table either ascending or descending based on that field.
Sub sorter ()
Dim rn1, k1, hd As Range
Dim vl, typ As Integer
typ = 1
Set rn1 = Application.InputBox ("Select Range", "List", Type: =8)
Set hd = Range (rn1.Cells (1, 1), rn1.Cells (1, rn1.Columns.Count))
Set k1 = Application.InputBox ("Select single field", "Sort", Type: =8)
'Checkup - is the cell selected single and a heading or not
If k1.Cells.Count > 1 Or Union (hd, k1).Address <> hd.Address Then
Exit Sub
End If
'Option to sort ascending or descending
vl = MsgBox ("To sort Ascending press YES. Else, NO", vbYesNo,
"Sort")
If vl <> vbYes Then typ = 2
rn1.Sort k1, typ, Header: = xlYes
End Sub
The line rn1.sort is the only line new where k1 is the desired field
heading cell and typ is 1 or 2 for sorting ascending or descending
respectively. The header being present, the header parameter has to be
given. All other parameters are optional.
When the program executes, it first asks for the range. This we enter as
shown below:
84
It then asks for the field heading. Let us choose say the designation field
cell as shown:
85
The AutoFilter Method
86
We will filter this range based on the designation and Locality.
Sub autfltr ()
Dim rn1 As Range
Set rn1 = Application.InputBox ("Select Range", "List", Type:=8)
rn1.AutoFilter 2, "Faculty", xlOr, "Trainer", True
rn1.AutoFilter 3, "R.A.Puram", , , True
The statement below makes the drop down to not be shown for Field 1
Drop down will be there for others. This feature is not possible in
Excel
It is only possible in VBA
rn1.AutoFilter 1, VisibleDropDown: = False
End Sub
Note: By setting only the visible drop down option, we can have filtering
only for selected fields if need be. This can prevent users from filtering
unwanted fields or those fields which should not be filtered.
87
The Text to Column Method
This is by large a very useful method for automation. The data is usually
separated for the delimiter option which is most often used. Let us
however illustrate both options.
Parameters
88
Decimal separator to use for
Decimal Separator Optional Variant numbers. The default setting is the
system setting.
Thousand separator to use for
Thousands Separator Optional Variant numbers. The default setting is the
system setting.
TrailingMinusNumbers Optional Variant Numbers that begin with minus sign.
We now write the code to separate the text using text to columns
option:
Sub textocoldelim ()
Dim rn1 As Range
Dim dlm As String
Set rn1 = Application. InputBox ("Select Range", "List", Type: =8)
dlm = InputBox ("Type the delimiter", "Separator")
Applying the text to column method
Rn1.TextToColumns Destination: =rn1.Range ("a1").Offset (0, 1), _
Data Type:=xlDelimited, Consecutive Delimiter: =True, _
Other: =True, Other Char: =dlm
End Sub
The destination is given as the adjacent column cell. This option is not
possible in Excel. The delimiter is asked for in the inputbox. The result
will be as shown below:
89
The Fixed Width Option
The individual values need to be separated based on the field width. This
is done as shown below:
Sub ttcflwth ()
Dim rn1 As Range
Set rn1 = Application.InputBox ("Select Range", "List", Type:=8)
rn1.TextToColumns Destination: =rn1.Range ("a1").Offset (0, 1), _
DataType :=xlFixedWidth
End Sub
90
To be more specific such as assigning the width, the data type for each
column, the syntax can be more extensively used as shown:
The syntax is very similar to the Delimiter option and is as shown below
as an example for which the explanation is given:
Explanation:
Each field or each column must be an array within the overall array.
Let us take the first field: Array (0, 1) Here 0 represents the starting
field Number and 1 represents the General Data type
Let us take the second field: Array (20, 1) Here 20 represents the
starting field Number and 1 represents the General Data type
Let us take the fourth field: Array (77, 3) Here 77 represents the
starting field Number and 3 represents the DMY Data type. This means
that the original data is a date represented in the dd-mm-yy format.
91
The general data type is sufficient for general values (i.e. text and
numbers). The data types are given by the numbers 1, 2, 3 etc. The list
of data types:-
1 xlGeneralFormat General
2 xlTextFormat Text
3 xlMDYFormat MDY Date
4 xlDMYFormat DMY Date
5 xlYMDFormat YMD Date
6 xlMYDFormat MYD Date
7 xlDYMFormat DYM Date
8 xlYDMFormat YDM Date
9 xlSkipColumn Skip Column (This option ensures that the field is omitted).
92