0% found this document useful (0 votes)
68 views69 pages

MS Excel VBA v2

This document provides an introduction to macro programming in Microsoft Excel 2010. It covers recording macros, the Visual Basic Editor interface, programming basics like manipulating objects and their properties, using loops and conditional statements, defining variables, and debugging errors. The chapters introduce key concepts like modules, procedures, objects, properties, and methods. It teaches how to automate tasks by programming macros in Visual Basic for Applications.

Uploaded by

jamuna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views69 pages

MS Excel VBA v2

This document provides an introduction to macro programming in Microsoft Excel 2010. It covers recording macros, the Visual Basic Editor interface, programming basics like manipulating objects and their properties, using loops and conditional statements, defining variables, and debugging errors. The chapters introduce key concepts like modules, procedures, objects, properties, and methods. It teaches how to automate tasks by programming macros in Visual Basic for Applications.

Uploaded by

jamuna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

11/5/2016

MS EXCEL 2010 – INTRODUCTION TO


MACRO PROGRAMMING
Contents
Chapter 1 ..................................................................................................... 1
Recording Macros ........................................................................................................ 1
Enabling Developer Tab in Excel .............................................................................. 1
Recording A Macro .................................................................................................. 3
Executing A Macro ................................................................................................... 4
Viewing Your Macro ................................................................................................ 5
Editing A Macro ....................................................................................................... 5
Attaching Code To Buttons ...................................................................................... 6
Saving A Macro-Enabled Workbook ......................................................................... 7
Macro Security Settings ........................................................................................... 8

Chapter 2 ..................................................................................................... 9
Introduction To Macro Programming .......................................................................... 9
What Is VBA? ........................................................................................................... 9
What Is A Macro? .................................................................................................. 10
What Is VBA Code? ................................................................................................ 10
What Is A Module? ................................................................................................ 11
What Are Procedures? ........................................................................................... 11
What Are Objects?................................................................................................. 12
What Are VBA Object Properties? .......................................................................... 13
What Are Object Methods In VBA? ........................................................................ 13
The Visual Basic Editor ............................................................................................... 14
Viewing The VBA Editor In Excel............................................................................. 14
Menu Bar ............................................................................................................... 15
Toolbar .................................................................................................................. 16
Project Window / Project Explorer ......................................................................... 17
Properties Window ................................................................................................ 18
Programming Window / Code Window .................................................................. 19
Immediate Window ............................................................................................... 19
Adding A VBA Module............................................................................................ 20

Microsoft Excel
Removing VBA Modules......................................................................................... 20
Object Browser ...................................................................................................... 22

Chapter 3 ................................................................................................... 24
Programming Basics .................................................................................................. 24
Workbook Object .................................................................................................. 24
Worksheet Object .................................................................................................. 24
Range Object ......................................................................................................... 26
Manipulating data ................................................................................................. 31
Using Message box ................................................................................................ 32
Using Input Box ..................................................................................................... 33
Debugging Errors ....................................................................................................... 34
Executing Code Line By Line ................................................................................... 34
Setting Up A Breakpoint......................................................................................... 35
Clearing A Breakpoint ............................................................................................ 35
Debug Mode .......................................................................................................... 36
Procedures ................................................................................................................ 37
Calling one procedure from another ...................................................................... 39

Chapter 4 ................................................................................................... 41
Defining Variables In VBA .......................................................................................... 41
What Is A VBA Variable .......................................................................................... 41
Why Use Variables? ............................................................................................... 41
Using Option Explicit .............................................................................................. 44
How To Declare A Variable .................................................................................... 48
Variables and data types ........................................................................................ 50
Variables and scope ............................................................................................... 54
Object Variables .................................................................................................... 55

Microsoft Excel
Chapter 5 ................................................................................................... 56
Using Loops ............................................................................................................... 56
Do...Loop Statements ............................................................................................ 56
For…Next Statements ............................................................................................ 57
For Each...Next Statements.................................................................................... 58
Speeding Up Loops ................................................................................................ 59

Chapter 6 ................................................................................................... 61
VBA IF Function ......................................................................................................... 61
Using a simple IF function in VBA ........................................................................... 61
Using a IF function with ELSE in VBA ...................................................................... 62
Using a IF function with ELSEIF and ELSE: in VBA .................................................... 63

Microsoft Excel
Preface

Macro Programming For Non Programmers (duration - 2 days)


Spreadsheet automation is an essential skill for Excel users who want to take their day to
day use of Excel to the next level. You will create a variety of macros learning how to best
automate repetitive tasks and programme solutions in Excel. Even if you
do not have any programming experience, don't worry - the course is for complete
beginners. All you need is to be a proficient Excel user.
This course aims to cover in detail the VBA programming language. You will be learn how
to program in VBA in order to customise your work environment in Excel. You will learn
form design, control structures and how to debug and test your VBA application before
using it in the work environment.
What You Will Learn

Recording Macros
The easiest way to learn is by recording a macro. Here users will learn the keys to
successful recording, running a macro, editing a macro and saving a macro enabled
workbook.

Visual Basic Editor


In this module the users will learn about what is code, what are modules for and how to
insert modules, what are procedures, what are Excel objects, object properties and object
methods. Here the Visual basic editor is introduced and the components of the VBE and
it’s functionality is explained.
 Menubar  Code Window
 Toolbar  Immediate Window
 Project Explorer  Adding / Removing Modules
 Properties Window  Object Browser

Programming Basics
Here, users will learn programming syntax to manipulate objects and it’s properties. Such
as copy and paste, entering text, numbers or formulas. How to trouble shoot macros.
 VBA terminology  Message & Input boxes
 Working With Workbooks  Debugging Errors
 Working With Worksheets  Executing Commands Line by Line
 Working With Range  Setting Up Breakpoints
 Entering Data & Formulas
Using Variables
When it comes to VBA variables, poor coding practices can lead to potential problems
down the road. This section explains what are variables and how to define variables.
 Understanding Variables  Using Option Explicit
 Why Use Varibles  Variables & Data Types
 Defining & Using Variables  Using Object Variables
 Scoping Of Variables

Using Loops
Users will learn how to execute a macro repeatedly using loops. Learn when to use the
right looping technique.
 For Next Loops  Looping With Unknown
 For Each Loops Iterations
 Looping With Specified Iterations  Terminating Loops Early
 Do Loops  Speeding Up Loops

Decision Making
In this lesson, users will learn how to create macros that can make decision. Decision
making process is an important part of macro programming because it can help to solve
practical problems.
 The IF Statement  Using IF for Multiple Conditions
 Using IF for Single Conditions

Microsoft Excel
Chapter 1
Recording Macros
The easiest way to create is macro is using the Macro Recorder. You do not need any
programming to do this. As long as you are performing the same things over and over
again, then the recorder will do just fine.

Enabling Developer Tab in Excel


The Developer tab is, by default, hidden by Excel. Therefore, unless you (or somebody
else) has added the Developer tab to the Ribbon, you have to make Excel show it in order
to have access to the appropriate tools when setting-up a macro.
In order to record and use macros (and other developer features), the first step is to
activate Developer Tab (or Developer Toolbar). This is done by,
Excel 2007:
 Click on Office button (top left)
 Go to Excel Options > click Popular
 Check “Show Developer Tab in Ribbon” (3rd Check box)

Microsoft Excel Page 1


Excel 2010/2013/2016:
 Click on File Menu (top left)
 Go to Options
 Select “Customize Ribbon”
 Make sure “Developer tab” is checked in right side area

This is the developer tab.

To Run macros To Record macros

This opens the To set security


Visual Basic Editor settings
window

Microsoft Excel Page 2


Recording A Macro
In order to write your first VBA program (or Macro), you need to know the language first.
This is where Excel’s tape recorder will help us.
Tape Recorder??
Yes. Excel has a built-in tape recorder, that listens and records everything you do, in
Excel’s own language, ie VBA.
Since we don’t know any VBA, we will use this recorder to record our actions and then we
will see recorded instructions (called as code in computer lingo) to understand how VBA
looks like.
While recording, avoid unnecessary steps if possible. Such as;
 Scrolling your worksheet
 Using arrows keys to navigate
 Right clicking within the worksheet area (this indirectly selects a range)

Step 1: Select any cell & start macro recorder


This is the easiest part. Just select any cell and go to Developer Tab & click on Record
Macro button.

Step 2: Give a name to your Macro


Specify a name for your macro. I called mine MakeMeRed. You can choose whatever you
want. Just make sure there are no spaces or special characters in the name (except
underscore). Click OK when done.

Step 3: Fill the current cell with red color


This is easy as eating pie. Just go to Home tab and fill red color in the current cell.

Microsoft Excel Page 3


Step 4: Stop Recording
Now that you have done the only step in our macro, its time to stop Excel’s tape recorder.
Go to Developer tab and hit “stop recording” button.

Executing A Macro
You can run the recorded macro from the Developer tab click Macros. Alternatively you
can use the keyboard shortcut ALT + F8.

From the macro dialog box, select the macro and click Run.

Microsoft Excel Page 4


Viewing Your Macro
To view your code, go to the Visual Basic Editor (ALT + F11). When you double click on
module1, the code window will be open on the right of window. You will be able to see
the code of your recorded macro.

Editing A Macro
Let’s copy the recorded macro and paste it below. We will edit the copied version just in
case something goes wrong.
Change the macro name and delete the unnecessary codes and change the Color code to
65535 as shown below.
Sub MakeMeYellow()
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub

Microsoft Excel Page 5


Attaching Code To Buttons
An alternative way of running a macro is using buttons. To insert an object into your
spreadsheet and then assign a macro to that object. From the insert tab > click Shapes
and choose your shape. Drag the mouse to draw the selected shape.

While the shape is selected, type in a description so that users will know which macro will
be executed when the shape is clicked. To assign a macro to the shape, right click on the
shape, and click Assign Macro. In the Assign Macro dialog box, select the macro & click
OK.

Microsoft Excel Page 6


Saving A Macro-Enabled Workbook
To save a workbook that contains a macro, you will need to save the workbook as a macro
enabled workbook. If you were to save it as a normal workbook, you will lose all the
macros. Not too worry as Excel will prompt you with the message below.
Caution! DO NOT click yes.

To save the workbook as a macro enabled workbook, from the File tab click
Save & Send (or Export if Excel 2013) > Change File Type > Choose Macro-Enabled
Workbook > click Save As and give your file a name.

When you re-open a file containing macros, remember to enable macros otherwise the
macros could be disabled and you will not be able to run them.

Microsoft Excel Page 7


Macro Security Settings
It is good practise to disable macros with notification. This gives you a choice on whether
to allow or disallow a macro to run. If you received a file containing macros from an
untrusted source, always disallow the macro to run. To check your security settings, from
the Developer tab > Macro security. You will see the following dialog box as shown below.

Choose the option > Disable all macros with notification. When opening a workbook
containing macros, Excel will then prompt you on whether to allow the macros to run.

To allow the macros to run click “Enable content” if the prompt is above the formula bar.
If the prompt is in the middle of the screen, click “Enable macros”.

Microsoft Excel Page 8


Chapter 2
Introduction To Macro Programming
Excel VBA allows you to automate various activities you do in Excel. We use Excel to
analyze data, create reports, prepare charts & presentations, do calculations and
understand information. When we are doing all these, we spend quite some time,
repeating same steps.
For example, we may prepare and email same type of report every week with different
data.
By using Excel VBA, we can cut down the time we spend repeating these steps and
improve our productivity.
Being able to create a basic macro in Excel is only the beginning in the process to become
a really efficient and productive user of macros and VBA. If you really want to unleash the
power of these tools, you must learn VBA due to the fact that, among others, recording a
macro sometimes simply doesn’t “cut it”.

What Is VBA?
VBA stands for Visual Basic for Applications. Just like you and I have a language, computer
programs too have their own language. VBA happens to be the language in which Excel
speaks. For that matter, VBA is also the language of MS Word, PowerPoint, Access and
other MS Office applications.
The prospect of learning new languages scares us a lot. But worry not, VBA is much easier
to learn than French, Spanish, German or Chinese. The main reason why VBA is easy to
learn is because it almost looks like plain English.
For example the following line says hello to you:
MsgBox "hello"
You use a programming language, such as VBA, to communicate with a computer. More
particularly, you communicate instructions to the computer. Visual Basic for Applications
is the language that allows you and me to communicate instructions to Excel.
Just like any language, VBA too has its own rules, grammatical structures & nuances. Once
you understand these, speaking VBA with Excel becomes as easy as chatting with your
friend over a drink.

Microsoft Excel Page 9


What Is A Macro?
Excel macros and Visual Basic for Applications are not exactly the same thing, although
they are closely related and, sometimes, people use them interchangeably.
While VBA is the language which Excel speaks (and understands). A macro is not a
programming language. A macro is a sequence of instructions that automates some
aspect of Excel. In other words, a Macro is a complete set of instructions given to Excel to
accomplish a pre-defined task.
For example, this is a macro for generating a report (written in plain English, not VBA)
 Open data.xls
 Take last 30 days of data
 Prepare a bar chart
 Copy the chart to a new workbook
 Save the workbook as a PDF
 Email it to boss
When we execute or run this macro, we end up generating the report & mailing it.

What Is VBA Code?


You perform actions in VBA by executing VBA code. You can generate VBA code in one of
the following 2 ways:
 By recording certain actions you perform in an Excel workbook by using the macro
recorder.
 By writing the VBA code in the Visual Basic Editor (VBE).
The following is a very basic example of VBA code. The comments near the top (in green
font) explain what the piece of code does.

Microsoft Excel Page 10


What Is A Module?
In broad terms, a module is the equivalent of a VBA container. In other words, it is where
Excel actually stores the VBA code.
You can check out which modules are stored in the Excel workbook you’re currently
working on in the Project Explorer (which is one of the sections of the Visual Basic Editor).
The following screenshot shows an example of the Project Explorer, where there is only
a standard module (called “Module1”).

Modules consists of procedures.

What Are Procedures?


In more technical terms, a procedure is a block of statements that is enclosed by a
particular declaration statement and an End declaration.
VBA supports two types of procedures:
 Sub procedures which perform an action in Excel.
 Function procedures which carry out calculations and return a value.
The declaration statement that begins a Sub procedure is “Sub”.

Microsoft Excel Page 11


For example, the following piece of VBA code (the comments near the top of the image
describe its basic purpose) is a Sub procedure. Notice the opening declaration statement,
the matching End declaration and how the block of statements is enclosed by these two
declarations.

The use of terms such as sub procedure, routine, program, procedure and macro can be
a little bit confusing and, generally, they’re used interchangeably.

What Are Objects?


There are more than 100 classes of objects that can be manipulated using Visual Basic for
Applications. Since your Excel workbook is nothing but a collection of objects, whenever
you want to make any change (like modify a cell’s value or recolor a chart), you need to
refer to the corresponding object and VBA manipulates these objects.
The following are some examples of objects in Visual Basic for Applications:
 Workbooks.
 Worksheets.
 Cell ranges.
 Charts.
 Pivot tables.

Microsoft Excel Page 12


What Are VBA Object Properties?
Objects have properties. These are the attributes, characteristics or qualities that can be
used to describe the object. Every object within Visual Basic for Applications has
properties. This makes sense, after all, properties determine things such as:
 How the object looks like.
 How the object behaves like.
 Whether you can or can’t see the object.
In the example below, the procedure hides the first sheet in the workbook. The object is
“Sheets(1)” where the visibility is set to False.

What Are Object Methods In VBA?


The method is the “something” which is done to the object. There’s no question that
knowing about VBA objects is extremely important. After all, Excel programming really
boils down to manipulating the objects that make up Excel.
Methods are the actions or operations you perform with an object (by or on the object).
Properties, on the other hand, are the attributes or characteristics you can use to describe
the object.
In the example below, the procedure adds a new sheet. The object is “Sheets” where the
a new sheet is added to the collection.

Microsoft Excel Page 13


The Visual Basic Editor
The Visual Basic Editor is not exactly the same as Excel. It is actually a separate application,
even though you’ll usually open it through Excel. In fact, in order for the VBE to be able
to run, Excel must be open. The main function of the VBE is to allow you to write and edit
VBA code.

Viewing The VBA Editor In Excel


To view the VBA editor, click Visual Basic from the developer tab. Alternatively you can
use keyboard short cut ALT + F11.

The basic VBE window can be divided in the following 6 sections, all of which I explain
below. In reality, there are more components than those which appear in this screenshot.

Microsoft Excel Page 14


Menu Bar
The menu bar, basically, contains several drop-down menus. Each of the drop-down
menus contains commands that you can use to interact and do things with the different
components of the Visual Basic Editor.

One thing you’ll notice when clicking on any menu, is that several commands have a
keyboard shortcut that is displayed at that point. Take a look, for example, at the Debug
menu and notice all the keyboard shortcuts that appear on the right side of this image.

Microsoft Excel Page 15


Toolbar
You’re probably aware that a toolbar contains on-screen buttons, icons, menus and other
similar elements that you can use while working with the VBE.

The toolbar that appears in the screenshot above is called the Standard toolbar. This is
the only toolbar that the Visual Basic Editor displays by default.
You can change all of these settings by going to the View menu and selecting “Toolbars”.
The Visual Basic Editor displays a menu with the 4 different toolbars and the option to
access the Customize dialog.

Microsoft Excel Page 16


Project Window / Project Explorer
The Project Window, also known as the Project Explorer, is useful for navigation purposes.

This is the section of the Visual Basic Editor where you’ll be able to find every single Excel
workbook that is currently open. This includes add-ins and hidden workbooks. More
particularly, each Excel workbook or add-in that is open at the moment appears in the
Project Explorer as a separate project.
In the screenshot below, the only project that appears is the Excel workbook
“Book 1. xlsm”. Within the Microsoft Excel Objects node, you can see that the Excel
workbook has 2 worksheets. Finally, this particular project contains 1 VBA module and,
therefore, the Modules node is visible.

You can expand or contract the items that appear in the outline by double-clicking on
them or by clicking on the “+” or “-” that appear to the left of each item, depending on
the case.

Microsoft Excel Page 17


How To Display The Project Window
If you can’t see the Project Explorer, you can make the Visual Basic Editor display it by
using any of the following methods:
Clicking on “Project Explorer” in the View menu.

Properties Window
The Properties Window (bottom left window) displays the properties of the object that is
currently selected in the Project Explorer and allows you to edit those properties.

Microsoft Excel Page 18


Programming Window / Code Window
As you may expect, the Code Window of the Visual Basic Editor is where your VBA code
appears, and where you can write and edit such code. At the beginning, though, the
Programming Window is empty as in the screenshot below.

There is a Code Window for every single object in a project. You can access the window
of a particular object by going to the Project Explorer and Double clicking on the object.

Immediate Window
The main purpose of the Immediate Window is to help you noticing errors, checking or
debugging VBA code. The Immediate Window is, by default, hidden.

Microsoft Excel Page 19


Adding A VBA Module
It is important to select a project to add module to first. Go to the Project Explorer and
select the project to which you want to add a module. For example, in the screenshot
below, a module would be added to “VBAProject (Book 1.xlsm)”, which is the only open
project.

Go to the Insert menu and select “Module”.

Removing VBA Modules


Go to the Project Window and right click module to remove > Remove

Microsoft Excel Page 20


Visual Basic Editor displays a dialog asking you whether you want to export the module
before actually removing it.

Most of the times, the reason why you’re removing a VBA module is because you don’t
need the VBA code within it. In those cases, click “No” (there is no Un-Do if you change
your mind later on). If, for any reason, you actually want to export the module,
click on “Yes”.

Microsoft Excel Page 21


Object Browser
The object browser displays the classes, properties, methods, events, and constants
available from object libraries and the procedures in your project. You can get Help for
the Object Browser by searching for Object Browser in Help.

Type in the Search Text Box the string that you want to use in your search. In the example
shown, worksheet is typed. Click the binoculars to search.

Method

Event

Properties

Microsoft Excel Page 22


Let say you want to know how to copy a worksheet.

Scroll to look for the Copy


method. Select Copy and click
the yellow Question mark.
The help window will display the
syntax and hopefully some
sample code.

Microsoft Excel Page 23


Chapter 3
Programming Basics
Workbook Object

Creating a workbook
To create a workbook in Visual Basic, use the Add method. The following procedure
creates a workbook. Microsoft Excel automatically names the workbook BookN, where N
is the next available number. The new workbook becomes the active workbook.
Sub AddOne()
Workbooks.Add
End Sub
To save the workbook to the current path, you can add another line of code.
Sub AddOne()
Workbooks.Add
ActiveWorkbook.SaveAs Filename:="Allsales.xls"
End Sub

Opening a Workbook
When you open a workbook using the Open method, it becomes a member of the
Workbooks collection. The following procedure opens a workbook named MyBook.xls
located in the folder named MyFolder on drive C.
Sub OpenUp()
Workbooks.Open("C:\MyFolder\MyBook.xls")
End Sub

Worksheet Object

Activating sheets by index number


An index number is a sequential number assigned to a sheet, based on the position of its
sheet tab (counting from the left) among sheets of the same type. The following
procedure uses the Worksheets property to activate the first worksheet in the active
workbook.
Sub FirstOne()
Worksheets(1).Activate
End Sub

Microsoft Excel Page 24


If you want to work with all types of sheets (worksheets, charts, modules, and dialog
sheets), use the Sheets property. The following procedure activates sheet four in the
workbook.
Sub FourthOne()
Sheets(4).Activate
End Sub

Activating sheets by name


You can identify sheets by name using the Worksheets properties. The following
statements activates Sheets1 in the active workbook.
Worksheets("Sheet1").Activate

Adding a New Sheet


To add a new sheet to the current workbook, the Add command. This adds a new sheet
before the activesheet.
Worksheets.Add
Specify where to add a new sheet (example before Sheet1)
Worksheets.Add before:=WorkSheets("Sheet1")
To add 2 new sheets
Worksheets.Add count:=2

Renaming the Current Sheet


You can rename the current sheet using the following codes;
 ActiveSheet.Name = "New Sheet"
 ActiveSheet.Name = Format(Now(), "mmm") ‘based on system date
 ActiveSheet.Name = Format(Now(), "mmm-yy") ‘based on system date

Microsoft Excel Page 25


Range Object

How to refer to all the cells on the worksheet


When you apply the Cells property to a worksheet without specifying an index number,
the method returns a Range object that represents all the cells on the worksheet. The
following Sub procedure clears the contents from all the cells on Sheet1 in the active
workbook.
Sub ClearSheet()
Worksheets("Sheet1").Cells.ClearContents
End Sub
How to refer to cells and ranges by using A1 notation
You can refer to a cell or range of cells in the A1 reference style by using the Range
property. The following subroutine selects the range A1:D5
Sub MyRange()
Range("A1:D5").Select
End Sub
The following table illustrates some A1-style references using the Range property.
Reference Meaning
Range("A1") Cell A1
Range("A1:B5") Cells A1 through B5
Range("C5:D9,G9:H16") A multiple-area selection
Range("A:A") Column A
Range("1:1") Row 1
Range("A:C") Columns A through C
Range("1:5") Rows 1 through 5
Range("1:1,3:3,8:8") Rows 1, 3, and 8
Range("A:A,C:C,F:F") Columns A, C, and F

Microsoft Excel Page 26


How to refer to cells by using index numbers
You can use the Cells property to refer to a single cell by using row and column index
numbers. This property returns a Range object that represents a single cell. In the
following example, Cells(6,1) returns cell A6 on Sheet1. The Value property is then set
to 10.
Sub EnterValue()
Worksheets("Sheet1").Cells(6, 1).Value = 10
End Sub

How to refer to cells by using shortcut notation


You can use either the A1 reference style or a named range within brackets as a shortcut
for the Range property. You do not have to type the word "Range" or use quotation marks,
as shown in the following examples.
Sub ClearRange()
Worksheets("Sheet1").[A1:B5].ClearContents
End Sub

How to refer to cells relative to other cells


A common way to work with a cell relative to another cell is to use the Offset property.
In this example, the contents of the cell that is one row down and three columns over
from the active cell on the active worksheet are formatted as double-underlined.
Sub Underline()
ActiveCell.Offset(1, 3).Font.Underline = xlDouble
End Sub
Note:
 ActiveCell.Offset(1, 0).Select ‘moves down one cell from activecell
 ActiveCell.Offset(-1, 0).Select ‘moves up one cell from activecell
 ActiveCell.Offset(0, 1).Select ‘moves right one cell from activecell
 ActiveCell.Offset(0, -1).Select ‘moves left one cell from activecell

Microsoft Excel Page 27


How to refer to multiple ranges
By using the appropriate method, you can easily refer to multiple ranges. You can refer
to multiple ranges with the Range property by inserting commas between two or more
references. The following example clears the contents of three ranges on Sheet1.
Sub ClearRanges()
Worksheets("Sheet1").Range("C5:D9,G9:H16,B14:D18").ClearContents
End Sub
Named ranges make it easier to use the Range property to work with multiple ranges. The
following example works when all three named ranges are on the same sheet.
Sub ClearNamed()
Range("MyRange, YourRange, HisRange").ClearContents
End Sub

How to refer to rows and columns


Use the Rows property or the Columns property to work with entire rows or columns.
These properties return a Range object that represents a range of cells. In the following
example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for
the range is then set to True.
Sub RowBold()
Worksheets("Sheet1").Rows(1).Font.Bold = True
End Sub
The following table illustrates some row and column references using the Rows and
Columns properties.
Reference Meaning
Rows(1) Row one
Rows All the rows on the worksheet
Columns(1) Column one
Columns("A") Column one
Columns All the columns on the worksheet

Microsoft Excel Page 28


Selecting and Activating Cells
When you work with Microsoft Excel, you usually select a cell or cells and then perform
an action, such as formatting the cells or entering values in them. In Visual Basic, it is
usually not necessary to select cells before modifying them.
Sub Labels()
Worksheets("Sheet1").Range("A1") = "Name"
Worksheets("Sheet1").Range("B1") = "Address"
End Sub
If you use the Select method to select cells, be aware that Select works only on the active
worksheet. If you run your Sub procedure from the module, the Select method will fail
unless your procedure activates the worksheet before using the Select method on a range
of cells. For example, the following procedure copies a row from Sheet1 to Sheet2 in the
active workbook.
Sub CopyRow()
Worksheets("Sheet1").Rows(1).Copy
Worksheets("Sheet2").Select
Worksheets("Sheet2").Rows(1).Select
Worksheets("Sheet2").Paste
End Sub

Working with the Active Cell


The ActiveCell property returns a Range object that represents the cell that is active. You
can apply any of the properties or methods of a Range object to the active cell, as in the
following example.
Sub SetValue()
Worksheets("Sheet1").Activate
ActiveCell.Value = 35
End Sub
You can use the Offset property to move the active cell. The following procedure inserts
text into the active cell in the selected range and then moves the active cell one cell to
the right without changing the selection.

Microsoft Excel Page 29


Selecting the Cells Surrounding the Active Cell
The CurrentRegion property returns a range of cells bounded by blank rows and columns.
In the following example, the selection is expanded to include the cells adjoining the
active cell that contain data. This range is then formatted with the Currency style.
Sub Region()
Worksheets("Sheet1").Activate
ActiveCell.CurrentRegion.Select
Selection.Style = "Currency"
End Sub

Resizing A Range
You can resize a current selection or an activecell using the Resize property. In the
example below the selection is resized to 5 rows and 3 columns.
ActiveCell.Resize(5, 3).Select

Example
Consider the spreadsheet below;

To select from A1 to E6, this is continuous data. You can use current region.
 Range("a1").CurrentRegion.Select
This is useful to select continuous range of data. However if your data has empty rows or
columns, then you will need to select from A1 to the last cell used by Excel.
To select from A1 to E12, you will need to select until Excel’s last cell.
 Range(Range("a1"), ActiveCell.SpecialCells(xlLastCell)).Select

Microsoft Excel Page 30


Manipulating data

Entering Values
To enter data in cell A1 in the active worksheet, we can use the following codes;
 Range("a1") = 100
 [a1] = 100
 Cells(1, 1) = 100
 ActiveCell = 100 (assuming the active cell is A1)
 ActiveCell.Offset(0,-1) = 100 (assuming the active cell is B1)

Entering formulas
To enter a formula, we can use the Formula property. To enter a formula in cell B5 you
can use the following codes;

 Range("b5").Formula = "=sum(B2:B4)"
 ActiveCell.Formula = "=sum(" & ActiveCell.Offset(-3, 0).Resize(3, 1).Address & ")"
The second method assumes that the formula will be entered in the active cell and uses
the Address property. This method is better as it does not hard code any cell references.
The drawback is that the cell references are absolute ie =SUM($B$2:$B$4).
To make the cell references relative, consider the code below;
 ActiveCell.Formula = "=sum(" & ActiveCell.Offset(-3, 0).Resize(3, 1).Address _
(rowabsolute:=False, columnabsolute:=False) & ")"
NOTE
RowAbsolute:=False removes the “$” for the rows
ColumnAbsolute:=False removes the “$” for the columns

Calculating a Result & Entering Value


If you want to calculate a result and enter the result instead of a formula, you can use the
worksheet function.
 ActiveCell = WorksheetFunction.Sum(ActiveCell.Offset(-3, 0).Resize(3, 1))

Microsoft Excel Page 31


Using Message box
Excel has available some useful functions that allow us to either inform the user (Message
Box) and/or collect information from the user (Input Box). The most common of these is
the Message box function. While this function is very informative it is also very easy to
use. For instance, to display a simple message to a user you would only need to use this:
Sub MessageBox
MsgBox "Hello, my name is David."
End sub
This is using the message box in it's simplest form. Notice that to tell Excel we want a
message box we use the abbreviation MsgBox. If we had other code after our MsgBox
function, our procedure would pause until the user has acknowledged the message.
The syntax for the MsgBox function is:
MsgBox(prompt, [buttons] , [title] , [helpfile], [context])
The only part of the MsgBox function that is required is the Prompt, all other arguments
are optional.
Let’s try something different. Enter a random number into cell A1. Enter the following
code;
MsgBox "Entered value is " & Range("A1").Value
Assuming you entered the value 12 in cell A1, the message box will look like this;

We used the & operator to concatenate (join) two strings. Although Range("A1").value is
not a string, it works here.

Microsoft Excel Page 32


To start a new line in a message box, you can use vbNewLine.
MsgBox "Line 1" & vbNewLine & "Line 2"
Alternatively you can use vbCrLF instead.
MsgBox "Line 1" & vbCrLf & "Line 2"

Using Input Box


Another very handy function is the InputBox function. This will allow us to collect a reply
from a user in the form of text.
Its syntax is:
InputBox(prompt, [title] , [default] , [xpos] , [ypos] , [helpfile], [context])
The only required argument is the Prompt and this would be the message you display to
the user.
Sub GetName()
InputBox ("My name is David. what is your?")
End Sub
This is the inputbox displayed;

The macro below will demonstrate what ever the user enters in the inputbox will be
displayed via the message box.
Sub GetName2()
UserName = InputBox("My name is David. what is your?")
MsgBox "Hello " & UserName
End Sub

Microsoft Excel Page 33


Debugging Errors
When you write a macro, you need to test it and correct any errors in the macro. This
process is called debugging. The process of debugging a macro in VBA is the same as
debugging in any other programming language. All you need to do is step through the
macro, one command at a time, and make sure it works as you think it should. You do this
by viewing both the windows for your macro and a test worksheet. As you step through
the macro (using the commands available in the Debug menu of the VBA Editor), you can
correct any errors you locate.
As you are debugging macros, you need to make sure you think through every possible
way the macro could be used and all the possible conditions that could exist at the time
the macro is invoked. Try the macro out in all these ways and under all these conditions.
In this way, you will make your macro much more useful.

Executing Code Line By Line


To execute your macro line by line. To be able to view both the Excel window and the
code window, resize each window so that it occupies 50% of the screen as shown below.

This makes it easier to see what each line of code does. To execute the code line by line,
from the code window press “F8”. Each time F8 is pressed one line of code is executed.

Microsoft Excel Page 34


Setting Up A Breakpoint
A breakpoint is a selected line of code that once reached, your program will momentarily
become suspended. Once suspended, you are able to use VBA's debugging environment
to view the status of your program, step through each successive line of code, continue
execution of the code, or halt execution of the code.
You can create as many breakpoints in your code as you want. Breakpoints are particularly
useful when you want to suspend your program where you suspect a problem/bug exists.
To set a breakpoint, find the line of code where you'd like to suspend your program.
Left-click in the grey bar to the left of the code. A red dot should appear and the line of
code should be highlighted in red.

Clearing A Breakpoint
A breakpoint in VBA is indicated by a red dot with a line of code highlighted in red.
To clear a breakpoint in Excel 2013, left-click on the red dot next to the line of code that
has the breakpoint.

Now, the breakpoint is cleared and the line of code should look normal again.

Microsoft Excel Page 35


Debug Mode
When you hit a run time error, click Debug to see which part of the code caused the error.

The part of code that COULD cause the problem is then highlighted in yellow.

The Reset button

If this is not the cause of the error, you will need to click the reset command to get out of
break mode. If there is an error in the code, correct the error.

Microsoft Excel Page 36


Procedures
Protecting & Unprotecting a Workbook
When protecting a workbook, the structure of the workbook is protected and
NOT THE CONTENTS of the worksheet.
To protect and unprotect the active workbook use the following code;
 ActiveWorkbook.Protect
 ActiveWorkbook.UnProtect
The code below protects the active workbook for the structure & window with a
password 1234.
 ActiveWorkbook.Protect "1234", True, True
 ActiveWorkbook.UnProtect "1234" (there is no need for the true, true)

Protecting & Unprotecting the active Worksheet


When protecting the worksheet, the contents of the worksheet is protected.
To protect and unprotect the active worksheet use the following code;
 ActiveSheet.Protect
 ActiveSheet.UnProtect
To protect with a password “1234”
 ActiveSheet.Protect “1234”
 ActiveSheet.UnProtect “1234”

Unlocking cells
When a worksheet is protected, you cannot make changes to any cells unless the cells are
unlocked.
 Range("c2").Locked = False

Counting Worksheets
Knowing how many sheets you have will be useful if you need to cycle thru all the sheets
whether protecting sheets, getting data, or even unhiding hidden sheets. The code below,
displays the number of sheets in a message box.
 MsgBox Worksheets.Count

Microsoft Excel Page 37


Counting Rows
The following codes will count the number of rows and displays the result in a message
box;
 MsgBox Range("a1:a5").Rows.Count (within the range a1 to a5)
 MsgBox Selection.Rows.Count (within the selected range)
 MsgBox Cells.Rows.Count (within the whole sheet)

Locating the last row containing data


Knowing the last row containing data is useful when you need to add more data in your
worksheet. You would not want your macro to override existing data. The macro below
locates the last row containing data in column A.
Sub LastRow()
Cells(Rows.Count, 1).End(xlUp).Select
End Sub
To locate the next row below the last row, just tweak the macro to select the
cell below it.
Sub LastRow2()
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
End Sub

Copying & Pasting


Copying data and pasting to another range is something common. In the example below,
data is copied from the first sheet and pasted in the second sheet. Here the sheets are
selected by their index (position)
Sub Copy1()
Sheets(1).Range("a1:b4").Copy ‘selects the range to copy
Sheets(2).Select ‘ selects the second sheet
Range("a1").Select ‘selects the cell to paste to
ActiveSheet.Paste ‘paste data
End Sub
This can be a bit slow. The faster method is to copy and provide the destination to paste.
Sub Copy2()
Sheets(1).Range("a1:b4").Copy Sheets(2).Range("a1")
End Sub

Microsoft Excel Page 38


Calling one procedure from another
When coding a big project, it is good to write smaller individual procedures / macros
because writing them is much easier. Testing and trouble shooting them is also far easier.
Once the macros are ready, you can string the entire project by running the macros
consecutively using the Call statement.
The other advantage of creating smaller individual macros is that you can use them again
for other macros without re-writing them again.
Consider the 3 macros below.
This macro selects the data range assuming that the first row is always located in row 3.
Sub SelectRange()
Range("b3").CurrentRegion.Select
End Sub
This macro bolds the top row, last row and the last column of the data range.
Sub ApplyBold()
Dim Rgn_Rows As Integer
Dim Rgn_Cols As Integer
Rgn_Rows = Selection.Rows.Count
Rgn_Cols = Selection.Columns.Count
Cells(3, 1).Resize(1, Rgn_Cols).Font.Bold = True
Cells(3 + Rgn_Rows - 1, 1).Resize(1, Rgn_Cols).Font.Bold = True
Cells(3, Rgn_Cols).Resize(Rgn_Rows, 1).Font.Bold = True
End Sub
This macro creates the borders. (You can record this macro)
Sub CreateBorders()
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.Weight = xlThin
End With

Microsoft Excel Page 39


With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.Weight = xlThin
End With
End Sub
To run just one macro that run all the 3 macros above, use the following code;
Sub DoAll()
Call SelectRange
Call ApplyBold
Call CreateBorders
End Sub
Of course the sequence is important!

Microsoft Excel Page 40


Chapter 4
Defining Variables In VBA
One of VBA’s main purpose is to manipulate data. This data is generally stored in the
computer’s memory. You can store data in 2 places;
 Objects
 Variables

What Is A VBA Variable


A variable is, broadly, a storage location paired with a name and used to represent a
particular value. As a consequence of this, variables are a great way of storing and
manipulating data. To declare variables appropriately in VBA, you need to;
 Determine the way in which the data is stored, and how do you actually want to
store the data.
 Determine which macro, or part of a macro, can use that variable. This refers to
the variable scope and life.
 How do you name VBA variables.

Why Use Variables?


There are a few reasons for this, but the strongest has to do with Excel VBA data types.
The following are the main points that explain why, from these perspective, you should
get used to declaring variables when working in Visual Basic for Applications:
 VBA data types determine the way in which data is stored in the computer’s
memory.
 You can determine the data type of a particular VBA variable when declaring it.
However, you can also get away with not declaring it and allowing Visual Basic for
Applications to handle the details.
 If you don’t declare the data type for a VBA variable, Visual Basic for Applications
uses Variant (the default data type).
 Despite being more flexible than other data types, and quite powerful/useful in
certain circumstances, relying always on Variant has some downsides. Some of
these potential problems include inefficient memory use and slower execution of
VBA applications.
When you declare variables in VBA, you tell Visual Basic for Applications what is the data
type of the variable and this makes your macro run faster and use memory more
efficiently.

Microsoft Excel Page 41


Declaring Variables Allows You To Use The AutoComplete Feature
Let’s take a look at the following piece of VBA code. This is the first section of a VBA Sub
procedure (named Variable_Test) suggested as example by Microsoft.

Let’s imagine that you’re typing these statements and are currently at the following point:

Theoretically, you must type the whole name of the variable: “Variable_One”. However,
declaring the VBA variable previously allows you to take advantage of a keyboard
shortcut: “Ctrl + Space”. Once you’ve typed the first few (can be as little as 2 or 3) letters
of a declared variable name, you can press “Ctrl + Space” and the Visual Basic Editor does
one of the following:
 As a general rule, the VBE completes the entry.
 If there is more than 1 option available, the Visual Basic Editor displays a list of
possible matches to complete the entry.
In the case above, using the “Ctrl + Space” shortcut results in the Visual Basic Editor
displaying a list of possible matches to complete the entry as shown below.

Notice how the list above, in addition to Variable_One and Variable_Two, also includes
other reserved words and functions.

Microsoft Excel Page 42


Declaring Variables Makes VBA Carry Out Additional Error Checking
Some errors in Visual Basic for Applications may be very difficult to spot, particularly in
large or complex VBA applications. By declaring your VBA variables and defining their data
type, you get some additional help from Visual Basic for Applications.
The most common type of error that VBA can catch this way is data-typing errors. These
errors are caused by incorrectly assigning certain information to a particular variable.
More precisely, this usually happens when the assignment results in a mismatch between
the following:
 The data type of the variable
 The type of the data assigned to the variable.
The following are some examples of how this can occur:
 You declare an Integer or Byte variable, but try to assign a string to it. The Integer
and Byte data types are designed to store certain integers, not strings.
 You declare a Boolean variable, but try to assign a large integer to it. Variables of
the Boolean data type can only be set to the 2 Boolean values (TRUE and FALSE).

Declaring Variables Improves Code Readability, Makes Debugging Easier And Reduces
The Risk Of Certain Mistakes
whenever you declare VBA variables explicitly, you generally place all the variable
declarations at the beginning of a module or procedure. This improves the readability of
your VBA code.
Explicitly declaring all variables reduces the incidence of naming-conflict errors and
spelling mistakes. Naming-conflict errors are quite dangerous. If you don’t declare VBA
variables, there is a higher risk of accidentally over-writing or wiping out a pre-existing
variable when trying to create a new one.
Spelling mistakes can also create big problems. One of the main ways in which taking
measures to declare variables always helps you reduce spelling mistakes.
Variable declaration also helps reduce spelling mistakes by capitalizing all the lower-case
letters (in a variable name) that were capitalized at the point of the declaration.
To see how this works, let’s go back to the VBA code for the Variable_Test macro. Let’s
assume that you type the name of Variable_One without capitalizing (as shown below):

Microsoft Excel Page 43


Once you complete the statement, the Visual Basic Editor automatically capitalizes the
appropriate letters. This looks as follows:

Using Option Explicit


Visual Basic for Applications has a particular statement that forces you to declare any
variables you use. It’s called the Option Explicit statement.
Whenever the Option Explicit statement is found within a module, you’re prevented from
executing VBA code containing undeclared variables.
The Option Explicit statement just needs to be used once per module. In other words:
 You only include 1 Option Explicit statement per module.
 If you’re working on a particular VBA project that contains more than 1 module,
you must have 1 Option Explicit statement in each module.
Just type “Option Explicit” at the beginning of the relevant module, and before declaring
any procedures. The following image shows how this looks like:

Once you’ve included the Option Explicit statement in a module, Visual Basic for
Applications doesn’t execute a procedure inside that module unless absolutely all the
variables within that procedure are declared. If you try to call such procedure, Excel
displays the following compile-time error message:

Microsoft Excel Page 44


In addition to the reasons provided above to support the idea that you should declare
your VBA variables, there is an additional advantage when using the Option Explicit
statement and having to declare absolutely all of your variables:
The Visual Basic Editor automatically checks the spelling of your VBA variable names.
Let’s go back to the Variable_Test macro that was introduced above. The following
screenshot shows the full Sub procedure:
Notice how, at the beginning of the Sub procedure, the variables Variable_One and
Variable_Two are declared.

Notice, furthermore, how each of these variables appears 2 times after being declared:

Let’s assume that while writing the VBA code, you made a typo when writing the name of
the VBA variable Variable_One (you typed “Variable_Ome”). In such a case, the code of
the Variable_Test macro looks as follows:

Microsoft Excel Page 45


Such small typos can be difficult to spot in certain situations. This is the case, for example,
if they’re present within the VBA code of a large Sub procedure or Function procedure
where you’re working with several different variables. This may be a big problem.
Excel interprets the different spellings as different variables (for example, Variable_One
and Variable_Ome). In other words, Excel creates a new variable using the misspelled
name. This leads to having several variables even though you think you only have one
and, in certain cases, may end in the macro returning the wrong result.
However, when you misspell the name of a VBA variable while having the Option Explicit
statement enabled, Excel warns you about it. The following image shows the error
message that is displayed when I try to run the Variable_Test macro with the typo shown
above. Notice how the Visual Basic Editor:
 Clearly informs you that there is an undefined variable.
 Highlights the element of the VBA code where the mistake is.

Microsoft Excel Page 46


However, the Visual Basic Editor is highly customizable. One of the customizations you
can make is have the VBE always require that you declare your variables. The Visual Basic
Editor does this by automatically inserting the Option Explicit statement at the beginning
of any VBA module.
You can get to the Options dialog of the Visual Basic Editor by clicking on the Tools menu
and selecting “Options…”.

The Visual Basic Editor should display the Editor tab of the Options dialog by default.
Otherwise, simply click on the relevant tab at the top of the dialog.
Within the Editor tab, you simply need to enable “Require Variable Declaration” by ticking
the box next to it. Then, click the OK button at the lower right corner of the dialog to
complete the operation.

Note that enabling Require Variable Declaration option only applies to modules created
in the future. In other words, Require Variable Declaration doesn’t insert the Option
Explicit statement in previously existing modules that were created while the option
wasn’t enabled.

Microsoft Excel Page 47


How To Declare A Variable
The most common way of declaring a variable explicitly is by using the Dim statement.
You’ve already seen this type of statement within the Variable_Test macro shown above.
In that particular case, the Dim statement is used to declare the Variable_One and
Variable_Two variables as follows:

Both variables are being declared as being of the Integer data type.
3 other keywords (in addition to Dim) may be used to declare a VBA variable explicitly:
 Static.
 Public.
 Private.
The basic structure of the declaration statement is the same:
Keyword Variable_Name As Data_Type
 “Keyword” is any of the above keywords: Dim, Static, Public or Private.
 “Variable_Name” is the name you want to assign to the variable.
 “Data_Type” makes reference to the data type of the variable. This element is
optional, but recommended.
The question of which is the exact keyword that you should use to declare a particular
VBA variable depends, mostly, on the scope and life you want that particular variable to
have.
The following table shows the relationship between the 4 different statements you can
use to declare a VBA variable and the 3 different scopes a variable can have:

Microsoft Excel Page 48


The Dim statement is the most common way to declare a VBA variable whose scope is
procedure-level or module-level.
However, you can also use a single Dim statement to declare several variables. In such
cases, you use a comma to separate the different variables.

Example
Excel will still allow us to run our code without using variables, it is not a must! But having
said this it is very bad programming to not use variables.
Let's use an example to highlight the above.
Sub NoVariable()
Range("A1").Value = Range("B2").Value
Range("A2").Value = Range("B2").Value * 2
Range("A3").Value = Range("B2").Value * 4
Range("B2").Value = Range("B2").Value * 5
End Sub
In the above code, Excel would need to retrieve the value from cell B2 five times. It would
also mean if we had many other procedures using the same value i.e B2, it would need to
retrieve it's value even more times. There is a lot of editing to be done if we were to
change from wanting B2 value to say, B5 value. It is messy code.
To declare a variable, use "Dim" followed by our chosen variable name then the word
"As" followed by the variable type. Let's now use a variable to store the value of cell B2!
Sub WithVariable()
Dim iMyValue as Integer
iMyValue = Range("B2").Value
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
Range("A3").Value = iMyValue * 4
Range("B2").Value = iMyValue * 5
End Sub
In the above code Excel only needs to retrieve the value of cell B2 once. To edit our code
we only need to change it in one place. It is easier to read.

Microsoft Excel Page 49


Identifying variable types
When naming your variables, you can start a variable's name with one to three-letter
prefix that could identify the data type used. Here are a few suggestions:

Variables and data types


A Variable is used to store temporary information that is used for execution within the
Procedure, Module or Workbook. Before we go into some detail of Variables, there are
a few important rules that you must know about.
 A Variable name must Start with a letter and not a number. Numbers can be
included within the name, but not as the first character.
 A Variable name can be no longer than 250 characters.
 A Variable name cannot be the same as any one of Excel's key words. By this, I
mean you cannot name a Variable with such names as Sheet, Worksheet etc.
 All Variables must consist of one continuous string of characters only. You can
separate words by either capitalising the first letter of each word, or by using the
underscore characters if you prefer.
To declare a variable you use the DIM statement. Here the variable is declared but not
the data type.
Dim Date_Of_Birth
To declare the variable and the data type.
Dim Date_Of_Birth as Date

Microsoft Excel Page 50


If you declare your variable as Byte, it will be able to hold a value of 0 to 255. Going beyond
255 will cause an overflow. See error message below.

Therefore it is important to know what values you are expecting and declare using the
correct data type.

Microsoft Excel Page 51


The following table shows the supported data types, including storage sizes and ranges.
Data type Storage size Range
Byte 1 byte 0 to 255
Boolean 2 bytes True or False
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,647
(long integer)
LongLong 8 bytes -9,223,372,036,854,775,808 to
(LongLong 9,223,372,036,854,775,807 (Valid on 64-bit
integer) platforms only.)
LongPtr 4 bytes on -2,147,483,648 to 2,147,483,647 on 32-bit
(Long integer on 32-bit systems, -9,223,372,036,854,775,808 to
32-bit systems, systems, 8 9,223,372,036,854,775,807 on 64-bit systems
LongLong integer bytes on 64-
on 64-bit systems) bit systems
Single 4 bytes -3.402823E38 to -1.401298E-45 for negative
(single-precision values; 1.401298E-45 to 3.402823E38 for
floating-point) positive values
Double 8 bytes -1.79769313486231E308 to
(double-precision -4.94065645841247E-324 for negative values;
floating-point) 4.94065645841247E-324 to
1.79769313486232E308 for positive values
Currency 8 bytes -922,337,203,685,477.5808 to
(scaled integer) 922,337,203,685,477.5807

Microsoft Excel Page 52


Data type Storage size Range
Decimal 14 bytes +/-79,228,162,514,264,337,593,543,950,335
with no decimal point;
+/-7.9228162514264337593543950335 with 28
places to the right of the decimal; smallest non-
zero number is
+/-0.0000000000000000000000000001
Date 8 bytes January 1, 100 to December 31, 9999
Object 4 bytes Any Object reference
String 10 bytes + 0 to approximately 2 billion
(variable-length) string length
String Length of 1 to approximately 65,400
(fixed-length) string
Variant 16 bytes Any numeric value up to the range of a Double
(with numbers)
Variant 22 bytes + Same range as for variable-length String
(with characters) string length
(24 bytes on
64-bit
systems)
User-defined Number The range of each element is the same as the
(using Type) required by range of its data type.
elements

Microsoft Excel Page 53


Variables and scope

Procedure Scope
Procedure scope means that a variable is accessible (it can be read and modified) only
from within the procedure in which it is declared.
Sub StaticVariable()
Dim iMyValue as Integer
iMyValue = 10
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
End Sub

Module Scope
Module scope means that a variable can be declared before and outside of any procedure
in a regular code module. If you use Private or Dim to declare the variable, only
procedures that are in the same module can access that variable. Since a module level
variable is not part of any procedure, it will retain its value even after the procedure that
changes its value has terminated. Module-level variables is declared at the top of the
module above the first procedure.
Private iMyValue As Integer
Sub PrivateVariable()
iMyValue = 10
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
End Sub

Project Scope
Public variables have the broadest scope of all variables. A public variable is recognized
by every module in the active workbook. Project scope variables are those declared using
the Public keyword.
Public iMyValue As Integer
Sub PublicVariable()
iMyValue = 10
Range("A1").Value = iMyValue
Range("A2").Value = iMyValue * 2
End Sub

Microsoft Excel Page 54


Object Variables
An object variable is a variable that represents an entire object, such as a range or a
worksheet. Object variables are important for two reasons:
 They can simplify your code
 The run much faster
Object variables, like normal variables, are declared with the Dim or Public statement for
example:
 Public InputArea as Range
To see how object variables simplify your code, examine the following procedure, which
was written without using object variables:
Sub NoObjVar()
Worksheets(“Sheet1”).Range(“A1”).Value = 123
Worksheets(“Sheet1”).Range(“A1”).Font.Bold = True
Worksheets(“Sheet1”).Range(“A1”).Font.Italic = True
End Sub
That is a lot of typing. You can re-write the procedure like this:
Sub ObjVar()
Dim MyCell As Range
Set MyCell = Worksheets(“Sheet1”).Range(“A1”)
MyCell.Value = 123
MyCell.Font.Bold = True
MyCell.Font.Italic = True
End Sub
After the variable MyCell is declared as a Range object, the Set statement assigns an
object to it. This simplifies coding and your code now executes more quickly.

Set Object Variables to Nothing


It is good practice to set all object variables to Nothing at the end of the lifecycle of the
variable even though Visual Basic will destroy all variables and pointers automatically
once the routine has ended.
It is possible to have an object variable allocated to memory after the event of an error
occurring. If the error handler allows the procedure to continue, it may be necessary to
re-set the same object variable. This is when an object should be destroyed and then re-
initialised.
At the end of a procedure, destroy all object variables in the following manner:
 Set objWSheet = Nothing

Microsoft Excel Page 55


Chapter 5
Using Loops
The purpose of a loop is to get Excel to repeat a piece of code a certain number of times.
For example, you may have to loop through a list of data on a worksheet. How many times
the code gets repeated can be specified as a fixed number
(e.g. do this 10 times), or as a variable (e.g. do this for as many times as there are rows of
data).
Loops can be constructed many different ways to suit different circumstances. Often the
same result can be obtained in different ways to suit your personal preferences.
There are two basic kinds of loops, both of which are demonstrated here: Do…Loop and
For…Next loops. The code to be repeated is placed between the key words.

Do...Loop Statements
You can use Do...Loop statements to run a block of statements an indefinite number of
times. The statements are repeated either while a condition is True or until a condition
becomes True.
Tips: To stop an endless loop, press ESC or CTRL+BREAK.
Do…While repeats statements while a condition is true
Do…Until repeats statements until a condition becomes true
To Search a Dynamic List or a List with an Unknown Number of Rows
This code moves down column A to the end of the list and bolds cells with a value of
5 and above. (This code assumes that each cell in column A contains a value)
Sub DoUntilLoop()
Range("A2").Select
Do Until IsEmpty(ActiveCell)
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Loop
End Sub

Microsoft Excel Page 56


Alternatively, you could use the Do While loop to achieve the same thing.
Sub DoWhileLoop()
Range("A2").Select
Do While ActiveCell <> ""
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Loop
End Sub

For…Next Statements
You can use For...Next statements to repeat a block of statements a specific number of
times. For loops use a counter variable whose value is increased or decreased with each
repetition of the loop.
To Search a List with a Constant, Known Number of Rows
This code moves down column A to the end of the list and bolds cells with a value of
5 and above:
Sub ForLoop()
Dim x As Integer
NumRows = Range("A2", Range("A2").End(xldown)).Rows.Count
Range("A2").Select
For x = 1 To NumRows
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Next
End Sub
Alternatively you could give control to the user to decide the range of cells to run the
macro. This means the user will have to select the range first before running the macro.
Sub ForLoop2()
Dim x As Integer
NumRows = Selection.Rows.Count
For x = 1 To NumRows
If ActiveCell >= 5 Then ActiveCell.Font.Bold = True
ActiveCell.Offset(1, 0).Select
Next
End Sub

Microsoft Excel Page 57


Protecting All Worksheets
The macro below will loop through all the sheets and protect each of them individually.
Sub ProtectALL()
For i = 1 To ActiveWorkbook.Sheets.Count
Sheets(i).Protect
Next i
End Sub
The following will unprotect the sheets.
Sub UnProtectALL()
For i = 1 To ActiveWorkbook.Sheets.Count
Sheets(i).Unprotect
Next i
End Sub

For Each...Next Statements


For Each...Next statements repeat a block of statements for each object in a collection or
each element in an array. Visual Basic automatically sets a variable each time the loop
runs.

Protecting & Unprotecting All Worksheets


Excel knows how many objects there are, therefore there is no need to perform a count.
Unlike the earlier macro.
Sub ProtectALL2()
For Each Worksheet In ActiveWorkbook.Sheets
Worksheet.Protect
Next
End Sub

Sub UnProtectALL2()
For Each Worksheet In ActiveWorkbook.Sheets
Worksheet.Unprotect
Next
End Sub

Microsoft Excel Page 58


Changing Case
Applications like Word, PowerPoint & Access are capable of changing text case.
Unfortunately you cannot do it for a range of cells in Excel. You can only do it using a
formula and it is on a cell by cell basis. The following macro below overcomes the
problem. (Microsoft should have thought of putting this command in Excel.)
Sub UpperCase()
Dim cell As Range
For Each cell In Selection.Cells
cell = UCase(cell)
Next
End Sub

Sub LowerCase()
Dim cell As Range
For Each cell In Selection.Cells
cell = LCase(cell)
Next
End Sub

Sub TitleCase()
Dim cell As Range
For Each cell In Selection.Cells
cell = Application.Proper(cell)
Next
End Sub

Speeding Up Loops
Loops should be avoided where possible as they can be pretty slow. Selecting ranges can
slow down a macro. Consider this macro running 15,000 times.

This is slow because this macro selects a cell 15,000 times & updates the screen each time
which causes the screen to flicker.

Microsoft Excel Page 59


Consider this macro where it does not select any cell. It runs much faster.

However if you want to retain the original macro and yet want it to run faster, consider
not updating the screen. This will avoid the flickering screen and speeds up the process.
Don’t forget to enable the screen updating after the complete process.

Microsoft Excel Page 60


Chapter 6
VBA IF Function
The IF function in VBA is one of the most frequently used of all statements. The IF function
checks if the specified condition is being met or not. The IF function in VBA works in a
slightly different manner from how it works in Excel. In Excel, the IF function does two
things : It checks whether the given condition evaluates to TRUE or FALSE and then returns
a value to use based on the evaluation i.e IF(condition, return_value_if_condition_true,
return_value_if_condition_false). However, the IF function in VBA does only the first part,
i.e. check if the condition evaluates to TRUE or FALSE. The steps to take in either scenario
as specified using the additional THEN statement.

Using a simple IF function in VBA


Here’s an example of the IF function. This piece of VBA code is simply checking whether
the condition specified (i.e. 1 > 4) evaluates to TRUE or FALSE. In this case, we have only
specified the steps to be completed when the condition evaluates to TRUE. In this case,
the result will be a message box being displayed on the screen. If the function were to
evaluate to FALSE, the VBA code will do nothing.
Sub IF_FUNCTION()
If 7 > 1 Then
MsgBox "7 is greater than 1"
End If
End Sub
The THEN statement is essentially a directive indicating that the steps immediately
following it are to be executed if the condition just before if evaluate to TRUE.
The IF function typically ends with an END IF declaration which lets the application know
that it is the last line of the IF function.

Microsoft Excel Page 61


Given below is a slightly shorter form of the IF function. Note that the END IF statement
has been eliminated in this and thus three lines of code has been merged into one.
Sub IF_FUNCTION_SHORT()
If 7 > 1 Then MsgBox "7 is greater than 1"
End Sub
However this form should be used only when there are no ELSE or ELSE IF statements are
needed. Let’s look at what they are and how they help enhance the IF function.

Using a IF function with ELSE in VBA


In the example given above, we saw that the IF function would be able to carry out steps
only if the condition evaluated to TRUE. But what if we wanted to specify the steps to be
carried out when either of the conditions were met. One way to achieve branching out of
an IF function is to use the ELSE statement. Simply put, the ELSE statement causes the
application to execute the steps mentioned in the ELSE block when the condition specified
in the IF clause evaluates to FALSE.
In the VBA code example below, the condition in the IF function evaluates to false, the
steps mentioned in the ELSE block are executed with the result that the message “1 is less
than 4″ gets displayed on the screen. Multiple steps can be added to the block to have
them all execute one after another.
Sub IF_ELSEIF_FUNCTION()
If 1 > 4 Then
MsgBox "1 is greater than 4"
Else:
MsgBox "1 is less than 4"
End If
End Sub

Microsoft Excel Page 62


Using a IF function with ELSEIF and ELSE: in VBA

The ELSE statement may be supported by ELSEIF statements. They are typically used to
check for specific conditions and if all of them evaluate to FALSE, the steps specified in
the ELSE condition will finally get executed. The IF statement will check for a given
condition. If that condition turns out to be FALSE, the condition specified in the first ELSEIF
statement will be checked. If that also turns out to be FALSE, the condition specified in
the second ELSEIF statement will be checked, and so on and so forth. If all conditions
specified in the IF and ELSEIF statements turn out to be FALSE, by default the steps
mentioned under the final ELSE: block will get executed. Please remember that if there
are multiple ELSEIF statements, the first one that evaluates to TRUE will get executed and
once completed, the code execution will move to the END IF statement. Even if there are
multiple ELSEIF conditions that evaluate to TRUE, only the first one that evaluates to TRUE

Sub IF_ELSEIF_ELSE_FUNCTION()
If < <condition_1>> Then
MsgBox "1 is greater than 4"
ElseIf < <condition_2 if condition_1 = FALSE >> Then
MsgBox "2 is greater than 4"
ElseIf < <condition_3 if condition_2 = FALSE >> Then
MsgBox "3 is greater than 4"
Else < <If_Everything_Fails>>:
MsgBox "1, 2 or 3 are lesser than 4"
End If
End Sub
In the example shown below, the IF condition is checked first. Since it evaluates to FALSE,
the first ELSEIF condition is evaluated, followed by the second. Since none of them
evaluate to TRUE, the steps mentioned in the ELSE: condition are executed.
Sub IF_ELSEIF_ELSE_FUNCTION()
If 1 > 4 Then
MsgBox "1 is greater than 4"
ElseIf 2 > 4 Then
MsgBox "2 is greater than 4"
ElseIf 3 > 4 Then
MsgBox "3 is greater than 4"
Else:
MsgBox "1, 2 or 3 are lesser than 4"
End If
End Sub

Microsoft Excel Page 63

You might also like