You are on page 1of 22

Object Model of Excel

Application

Workbook

Worksheet

Range Charts Controls Shapes

What is an Object in Excel?

Anything and everything in Excel is an object. Application itself is an object

What is an Excel Macro? What does it do?

A macro is a series of commands and functions (function: A prewritten formula that takes a value or
values, performs an operation, and returns a value or values. Use functions to simplify and shorten
formulas on a worksheet, especially those that perform lengthy or complex calculations.) that are stored
in a Microsoft Visual Basic module (module: A collection of declarations, statements, and procedures
stored together as one named unit. There are two types of modules: standard modules and class
modules.) and can be run whenever you need to perform the task. If you perform a task repeatedly in
Microsoft Excel, you can automate the task with a macro. For example, if you often enter long text
strings in cells, you can create a macro to format those cells so that the text wraps.

Macro & VBA?

A macro is a series of commands and functions. These commands and functions are written in a
programming language that is VBA.

VB, VBA and VBS

VBA is not to be confused with Visual Basic, Visual Basic is a stand-alone program that runs
independently. VBA, on the other hand, is part of an Office application, and therefore cannot work
without the Office Application. For example, VBA for Excel is part of the Excel Program, and cannot run
without Excel. There are many similarities in the language constructs however, and as already stated
VBA is highly compatible with VB.

Visual Basic Script – a variant of the Visual Basic Language widely used for Internet Applications.

Synonyms for Macro

A macro can also be called as a) Subroutine b) Procedure c) Program


How do you enable Developer Tab in Excel?

2007 : Office Buttion - Excel Options - Popular - Enable Developer Tab

2010 : File - Options - Customize Ribbon - Developer

What is Macro Recorder?

Microsoft Excel has a build-in macro recorder that translates your actions into VBA macro
commands. After you recorded the macro, you will be able to see the layout and syntax. Before you
record or write a macro, plan the steps and commands you want the macro to perform. Every action
that you take during the recording of the macro will be recorded - including the correction that you
made. (Exercise 1: Record a sample macro with few steps)

How do you record a macro?

View - Macros -Record Macro

Need to provide:

a) Macro Name

b) Shortcut Key (Optional)

c) Store Macro in: This Workbook/New Workbook/Personal Workbook

d) Macro Description (Optional)

How do we view the code for the macro or how do we open Visual Basic Editor?

We can use Alt+F11 or Developer - Visual Basic


Project Explorer

Code Window

Module

Properties Window

Open/Double click on Module (which is there under VBA Project on left hand side)

Text Colors in Code:

Blue: System reserved key words

Black: User code

Green: Comments (These lines do not get executed in the program, they just give some description
about the code. These lines start with ‘(single quote)).

What is a Module?

A module is a container for procedures. A procedure is a unit of code enclosed either between the Sub
and End Sub statement or between the Function and End Function statements.

What is the disadvantage with Macro Recording?

If you start recording a macro, it will remember everything you do within a program. Macro will record
all the codes that are there in one category. (Exercise 2: Change the font name while recording macro
and check the code.)

Code would look like this:

Sub Macro1()
'
' Macro1 Macro
'

'
Range("A1").Select
With Selection.Font
.Name = "Arial"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
End Sub

Record and Customize Macro

Customize the above code by removing unnecessary code.

Code would look like this:

Sub Macro1()
'
' Macro1 Macro
'

'
Range("A1").Select
With Selection.Font
.Name = "Arial"
End With
End Sub

What is “With” Statement and how to use?


The With…End With block instruction enables you to perform multiple operations on a single
object. This is another way to make the code execute more quickly and code styles more efficient.

Without using “WITH” Statement


Sub ChangeFont()
Selection.Font.Name = "Times New Roman"
Selection.Font.Size = 12
Selection.Font.Bold = True
Selection.Font.Italic = True
Selection.Font.ColorIndex = 5
End Sub

Using “WITH” Statement


Sub ChangeFont()
With Selection.Font
.Name = "Times New Roman"
.Size = 12
.Bold = True
.Italic = True
.ColorIndex = 5
End With
End Sub

Play your first macro.

Macro run options:

1. F5 – Run Macro
2. F8 – Line by line execution (line will be highlighted in yellow color, you would be able to see the
result, once the line is executed)
3. F9 – Break Mode (You can pause/break the macro on a particular line to debug the code)

Types of Errors

There are 3 types of VBA error that you may encounter when executing your macro. These are

a) Compile Errors,
b) Runtime Errors
c) Logical Errors (or 'bugs').

Compile Errors
Compile Errors are recognized by the VBA compiler as being illegal and therefore, are highlighted as
errors before your macro even starts to run. If a compile error is an incorrectly formatted line of VBA
code, the VBA editor will immediately detect and highlight this, as soon as you attempt to move your
cursor away from the specific line of code. Alternatively, a compile error may be detected at the time
you attempt to run your macro (but before execution has started).

A compile error is generally easy to fix, as the VBA compiler will give you information on the nature of
this type of VBA error.

Runtime Errors

Runtime errors occur during the execution of your code, and cause the code to stop running. This type
of VBA error is also generally easy to fix, as you will be given details of the nature of the error, and
shown the location that is highlighted in yellow color where the code has stopped running.

Examples:

5 - Invalid procedure call

6 - Overflow (An overflow results when you attempt an assignment that exceeds the
limits/range of the assignment's target/variable. Example: Integer data type cannot handle
the values outside -32763 to +32673 hence we cannot assign any value outside the range.)

7 - Out of memory

9 - Subscript out of range (this error arises if you attempt to access elements of an array
outside of the defined array size – Example: if you define an array indexed from 1 to 10,
then attempt to access entry no. 11)

11 - Division by zero

13 - Type mismatch (this error arises when you attempt to assign the wrong type of value to a
variable – Example: define i as an integer, then attempt to assign the string "text" to i

53 - File not found


(occurs when attempting to open a file)

Logical Errors
Logical Errors, otherwise known as 'bugs', occur during the execution of the VBA code, and allow the
code to continue to run to completion. However, the 'bug' may cause the macro to perform unexpected
actions or return an incorrect result. These errors are the most difficult to detect and fix, as there is no
way that the VBA compiler can identify and 'point to' the error, in the way that it does for compile and
runtime errors.

For example, you may accidentally code your macro to add together the wrong variables in a procedure.
The result would be incorrect, but the macro would usually continue to run to completion.

Understand VBA Terminology / Using Object Browser in VB Editor (F2)


Visual Basic For Applications: Objects and collections
Visual Basic For Applications is an (OO) object-oriented language. Performing a task in
Visual Basic for Applications (VBA) involves manipulating various types of
objects, each of which may have several different properties and methods. To perform a
task using VBA you return an object that represents the appropriate Excel element and
then manipulate it using the objects’ methods and properties.
Objects
A simple statement Range(“A1”).Select illustrates an important characteristic of
VBA. The syntax of many statements first specifies an object, Range(“A1”), and an
action upon it, Select. An object is a special type of variable that contains both data
and code and represents an element of Excel. Objects exist only in the computer’s
memory; they don’t appear in your code. There are many types of objects in VB, and
even more in Excel VBA. Excel objects that you will encounter include the
Application object which represents the Excel application itself, the Worksheet
object representing a worksheet, and the Range object representing an individual cell or
a rectangular range of cells (e.g. cells A2:C9 of the currently active worksheet).
Objects have types just as variables have data types.. Object types are called classes.
Workbook, Worksheet and Range are just a few of Excel’s object classes.
For Excel spreadsheets, functions etc. to be controlled and manipulated from a VBA
program, these “things” in Excel must have corresponding objects that can be referred to
in the program. The collection of objects corresponding to “things” in the Excel
application is called the Excel object model.
Methods
In VBA an action that an object can perform is referred to as a method. Thus a method of
an object is a procedure that carries out some action involving the object. Consider the
object Dog. To cause it to bark we could write
Dog.Bark.
However a Dog is capable of more than barking, for example we could have
Dog.Sit, Dog.Fetch.
In Excel, for example, the statement
ActiveCell.Clear
calls the Clear method of the ActiveCell object, which deletes the contents of the
cell. Like any other procedure, a method of an object can take one or more arguments, as
in this example:
ActiveCell.AddComment “This is a comment”
The list of methods that an object can perform depends on the object. For example, the
Range object supports about 80 different methods.
A method is accessed by following the relevant object with a dot and then the name of the
method.
Properties
An object can have properties. A property is a quality or characteristic of the object, e.g.
the length of the dog’s tail, the loudness of its bark. If you think of objects as the nouns
of VBA, then properties are its adjectives and methods are its verbs.
In Excel the properties may themselves be either primitive data types such as numbers,
strings or Boolean values, or may themselves be objects of some kind.
One of the many properties of the Application object is called Name, and is a read-only
string containing the name of the application, i.e. “Microsoft Excel”. It can be
accessed by adding a dot and the Name property after the object:
MsgBox Application.Name
The Application object also has a property called ActiveCell, which represents
the currently active cell in the active Excel worksheet. ActiveCell is an instance of
the object type called Range, and one of its properties is called Value and represents
the value (number, string or formula) held by the cell.
The statement
Application.ActiveCell.Value = “Hello”
will place the string “Hello” in the active cell.
Many properties of the Application object can be used without using the qualifier –
Application in this example - and the above statement could simply be written
ActiveCell.Value = “Hello”
Let’s consider in detail the statement

Worksheets(“sheet1”).Range(“A1”).Value = 3

Collections
A collection is an object that contains a group of related objects. Each object within the
collection is called an element of the collection. Collections are objects so have
associated methods and properties.
An example is the Sheets collection, which represents the worksheets in the active
workbook. This behaves a bit like an array, in that a specific worksheet in the collection
can be referenced using a numeric index:
Sheets(2).Activate
This makes the second worksheet active. Unlike a normal array, the index in a collection
object can be a name instead of a number:
Sheets(“Chart1”).Activate
When you want to work with a single object you usually return one member from the
collection. The property or method used to return the object is called an assessor. There are some
properties and methods that are unique to collections. The Count
property is one. It returns the number of elements in a collection.
Note: All instructions in VBA start with an Object and ends with a Property/Method

Property:

Syntax: Object.Property=New Value Example: Range(“A1”).Value=10

Method:

Syntax: Object.Method Example: Range(“A1”).Clear

Syntax: Object.Method Argument Example: Range(“A1”).Copy Destination:=Range(“C1”)

What is a Subroutine?

A Sub is a small chunk of code that you write to do a specific job. This starts with SUB
and ends with END SUB. You can run this Sub by pressing F5 in the VBA Editor, you
can run it by assigning the Sub to a button on a spreadsheet, and you can even run it
from the menu bar at the top of the Editor. In fact, there's quite a lot of different ways
you can run your Subs.

Synonyms for Subroutine:

i. Macro
ii. Procedure
iii. Program

Subroutine Naming Rules

 You must use a letter as the first character.


 You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the
name.
 Name can't exceed 255 characters in length.
 Generally, you shouldn't use any names that are the same as the functions, statements, and
methods in Visual Basic. You end up shadowing the same keywords in the language. To use an
intrinsic language function, statement, or method that conflicts with an assigned name, you
must explicitly identify it. Precede the intrinsic function, statement, or method name with the
name of the associated type library. For example, if you have a variable called Left , you can
only invoke the Left function using VBA.Left .
 You can't repeat names within the same level of scope. For example, you can't declare two
variables named age within the same procedure. However, you can declare a private variable
named age and a procedure-level variable named age within the same module.

Subroutine playing

i. F5 – Complete execution of Macro


ii. F8 – Line by Line execution of Macro
iii. F9 – Break Mode (it helps to stop the code on certain line)

Write your first macro and play it.

How to refer Excel Objects and their properties/methods? (Reference Styles in Excel Application)

1. Workbook Object:
a) ThisWorkbook : ThisWorkbook refers to the workbook where code is being written.
For example if we write: ThisWorkbook.Close, this closes the workbook where the
code has been written.
b) ActiveWorkbook: ActiveWorkbook refers to the workbook which is in active state
with active window. For example if we write: ActiveWorkbook.Close, this closes
the workbook which is in active status.

Note: In case of only one workbook open, ActiveWorkbook is same as ThisWorkbook.

c) WorkBooks(“WorkBook Name”): Using this style we can refer a WorkBook object


with its Name. For example if we write: WorkBooks(“Products”).Close, this closes
the workbook which has the name “Products” and this should be in open status.
d) WorkBooks(WorkBook Index): Using this style we can refer a WorkBook object with
its Index. For example if we write: WorkBooks(1).Close, this closes the workbook
which has the Index 1.
2. Worksheet Object:
a) Activesheet: Activesheet refers to the worksheet which is in active state. For
Example if we write: Activesheet.Name= “My Sheet” then it renames/ modifies the
Sheet Name Property of Activesheet name to “My Sheet”.
b) Sheets(“Sheet Name”): Using this style we can refer a sheet using its name. For
Example if we write: Sheets(“Sheet1”).Name= “My Sheet” then it renames/
modifies the Sheet Name Property of Sheet1 name to “My Sheet”
c) Sheets(Sheet Index): Using this style we can refer a sheet using its Index. For
Example if we write: Sheets(2).Name= “My Sheet” then it renames/ modifies the
Sheet Name Property of Sheet2 (Here Sheet2 is available in the second
position/index from the left side of Sheets Collection in the Workbook. If Sheet10
is available in the Second Position in Worksheets order, then it will consider
Sheet10’s Index as 2) name to “My Sheet”
3. Range Object:
a) ActiveCell: ActiveCell refers to the Cell which is in active state. For Example if we
write: ActiveCell.Value= “Microsoft Excel” then it modifies the value property of
the ActiveCell Value to “Microsoft Excel”.
b) Range(“Range Address”): Using this style we can refer a Range/Cell using its
Address. For Example if we write: Range(“A1”).Value= “Microsoft Excel” then it
modifies the Range Value Property of A1 to “Microsoft Excel”
c) Cells(Row Index, Column Index): Using this style we can refer a Single Cell using its
Row Index and Column Index. For Example if we write: Cells(1,1).Value= “Microsoft
Excel” then it modifies the Range Value Property of A1 to “Microsoft Excel”
Note:

 If you do not mention Workbook reference, macro will consider Activeworkbook


 If you do not mention WorkSheet reference, macro will consider ActiveWorkSheet

For example to refer the Value property & Delete Method for A1 Range object:

a) Range(“A1”).Value= “Microsoft Excel”


b) Range(“A1”).Delete

Understand Activecell, Activesheet & Activeworkbook:

a) Activecell: : ActiveCell refers to the Cell which is in active state. We can find only one
activecell for a given line of code.
b) Activesheet: Activesheet refers to the Sheet which is in active state. We can find only one
activesheet for a given line of code.
c) Activeworkbook: Activeworkbook refers to the Workbook which is in active state. We can
find only one Activeworkbook for a given line of code.

Activeworkbook Vs. Thisworkbook

ThisWorkbook refers to the workbook where code is being written while ActiveWorkbook refers to
the workbook which is in active state with active window. In case of only one workbook open,
ActiveWorkbook is same as ThisWorkbook.

Passing values from one range to another range:

Few examples are given below to copy/pass values from one range to another range:

a) Range(“A10”).Value= Range(“A1”).Value
Here Range(“A10”) is considered as destination reference and Range(“A1”) is source reference.
So, the value in A1 cell will be passed to A10 cell.
b) Sheets(“Sheet2”).Range(“A10”).Value= Sheets(“Sheet1”).Range(“A1”).Value
Here Sheet2 Range(“A10”) is considered as destination reference and Sheet 1 Range(“A1”) is
source reference. So, the value in Sheet1 A1 cell will be passed to Sheet 2 A10 cell.
c) ThisWorkbook.Sheets(2).Range(“A10”).Value= ThisWorkbook.Sheets(1).Range(“A1”).Value
Here Sheet2 Range(“A10”) is considered as destination reference and Sheet 1 Range(“A1”) is
source reference. So, the value in Sheet1 A1 cell will be passed to Sheet 2 A10 cell from
ThisWorkbook.
d) Workbooks(“2”).Sheets(2).Range(“A10”).Value= ThisWorkbook.Sheets(1).Range(“A1”).Value
Here WB Name 2, Sheet2 Range(“A10”) is considered as destination reference and
ThisWorkbook, Sheet 1 Range(“A1”) is source reference. So, the value in Sheet1 A1 cell will be
passed to Sheet 2 A10 cell.

 Note: The same code can be used to pass the values of collection of cells. For example
Range(“E1:E10”).Value=Range(“A1:A10”).Value

Copy and Paste Values from One Range to another Range

Copy Style 1:

Range(“a1:a3”).copy

Range(“e5”).activate

Activesheet.Paste

Application.CutcopyMode=False

The above style is not effective. There is another way of doing effective copy & paste

Copy Style2:

Range(“a1:a3”).Copy Destination:=Range(“e5”)

Copy method has Destination argument. If we mention the range object in destination argument, then
the copied content will be pasted in the destination range.

VARIABLES

To use some values in code, you must first create them. The computer memory is made
of small storage areas used to hold the values of your application. When you use a value
in your code, the computer puts it in a storage area. When you need it, you let the
computer know. The machine "picks it up", brings it to you, and then you can use it as
you see fit.
In the world of computer programming, a variable is a value you ask the computer to temporarily
store in its memory while the program is running.

Declaring a Variable
When writing your code, you can use any variable just by specifying its name. When you
provide this name, the computer directly reserves an area in memory for it. Microsoft
Visual Basic allows you to directly use any name for a variable as you see fit. Fortunately,
to eliminate the possibility of confusion, you can first let Visual Basic know that you will be
using a variable.

In order to reserve that storage area, you have to let the computer know. Letting the
computer know is referred to as declaring the variable. To declare a variable, you start
with the Dim word, like this:

Dim

A variable must have a name. The name is written on the right side of the Dim word.
There are rules you should follow when naming your variables:

 The name of a variable must begin with a letter or an underscore


 After starting with a letter or an underscore, the name can be made of letters,
underscores, and digits in any order
 The name of a variable cannot have a period
 The name of a variable can have up to 255 characters.
 The name of a variable must be unique in the area where it is used

There are some words you should (must) not use to name your variables. Those words
are reserved for the VBA internal use. Therefore, those words are called keywords. Some
of them are:

And (Bitwise) And (Condition) As Boolean ByRef Byte

ByVal Call Case CBool CByte CDate

CDbl CInt CLng Const CSng CStr

Date Dim Do Double Each Else

ElseIf End EndIf Error False For

Function Get GoTo If Integer Let

Lib Long Loop Me Mid Mod


New Next Not Nothing Option Or (Bitwise)

Or (Condition) Private Public ReDim REM Resume

Select Set Single Static Step String

Sub Then To True Until vbCrLf

vbTab With While Xor

As mentioned already, to declare a variable, type Dim followed by a name. Here is an


example:

Sub Exercise()
Dim Something
End Sub

This first line of code declares the variable (this is generally placed at the beginning of the
procedure).

Dim my_variable As Integer

Dim : declares the variable


my_variable : the name chosen for this variable (no spaces allowed)
As : declares the variable's type
Integer : variable type

Declaring these variables is not absolutely necessary, but it is recommended. It makes it easier to find
them, can help resolve problems, etc. In short, it's a good idea to get in the habit of declaring
variables correctly.

A variable's type indicates the nature of its contents (text, numbers, date, etc.).

Integer
Integer variables are used to store whole numbers.

Dim x As Integer
x=6
Range("A1").Value = x

String
String variables are used to store text.
Code:

Dim book As String


book = "bible"
Range("A1").Value = book

Double
A variable of type Double is more accurate than a variable of type Integer and can also store
numbers after the comma.
Code:

Dim x As Integer
x = 5.5
MsgBox "value is " & x

But that is not the right value! We initialized the variable with value 5.5 and we get the value 6.
What we need is a variable of type Double.

Code:

Dim x As Double
x = 5.5
MsgBox "value is " & x

Note: Long variables have even larger capacity. Always use variables of the right type. As a result,
errors are easier to find and your code will run faster.

Boolean
Use a Boolean variable to hold the value True or False.

Code:

Dim continue As Boolean


continue = True

If continue = True Then MsgBox "Boolean variables are cool"

The types of variables


Name Type Details Symbol

Byte Numerical Whole number between 0 and 255.

Integer Numerical Whole number between -32'768 and 32'767. %

Long Numerical Whole number between - 2'147'483'648 and 2'147'483'647. &

Currency Numerical Fixed decimal number between -922'337'203'685'477.5808 and @


922'337'203'685'477.5807.

Single Numerical Floating decimal number between -3.402823E38 and !


3.402823E38.

Double Numerical Floating decimal number between -1.79769313486232D308 and #


1.79769313486232D308.

String Text Text. $

Date Date Date and time.

Boolean Boolean True or False.

Object Object Microsoft Object.

Variant Any type Any kind of data (default type if the variable is not declared).

The symbols in the table above can be used to shorten our variable declarations.

For reasons of readability, we will not be using these in the lessons, but here is an example anyway :

Dim example As Integer


Dim example%

These two lines are identical.

Declaring Many Variables


In a regular application, it is not unusual to want to use many variables. Once again, you
should make it a habit to always declare a variable before using it. To declare a new
variable after declaring a first one, you can simply go to the next line and use the Dim
keyword to declare the new variable. Here is an example:

Sub Exercise()
Dim Something as String
Dim Whatever as Integer
End Sub

In the same way, you can declare as many variables as you want. Instead of declaring
each variable on its own line, you can declare more than one variable on the same line. To
do this, use one Dim keyword and separate the names of variables with commas. Here
are examples:

Sub Exercise()
Dim Father As String, Mother As String
Dim Some_Number As Integer, New_Number As Integer
End Sub
Notice that each line uses its own Dim keyword and every new line of declaration(s) must have a
Dim keyword.

VARIANT DATA TYPE

The VBA Variant Data Type can hold any type of data: numbers , text or object variables.

At first it would seem that a VBA Variant data type is a great innovation: it provides a flexible
and versatile way of storing any type of data you want to throw at it. However the Variant
variable is a false friend and is the downfall of many new VBA programmer. It is easy to fall into
the VBA Variant trap but with a few simple changes your code can become faster, more
readable and more stable.

My advice: always declare variables using the VBA Dim statement and always specify a data
type that isn't a Variant. Many VBA code samples in books or on internet forums don't follow this
simple rule but all the sample code on SpreadSheetSuperStar.com follows this coding standard.

Now back to why variant data types are a bad idea…

There are three reasons that using a VBA Variant is a very bad idea:

 Variants make VBA choose the underlying data type


 Variants are slow (because VBA has to choose)
 Variants use more memory (because VBA has to choose)

First, a variant data type allow VBA to select the underlying data type. A variant isn't really a
Swiss Army knife of variables. It is a wrapper for every other type of variable. VBA has to decide
if the variable you are assigning to the variant is a VBA text string, a numerical value like an
VBA integer, VBA double, VBA string or an object variable. Then it creates a integer, double,
string or object variable inside the variant data type container. This assessment takes time and
it takes additional memory to hold the information about the variable. So you are using more
computing power and memory. But that's not the worst part: the worst part is that sometimes
VBA assumes the wrong type of variable and that can cause problems.
When you specify a variable's data type it will avoid all this assessment and make your code
faster, more readable and more reliable.

OPTION EXPLICIT

We strongly recommend to use Option Explicit at the start of your Excel VBA code. Using Option Explicit
forces you to declare all your variables.

In order to ensure that you don't have any variables that start with the Dim keyword, you
can type Option Explicit at the very top of your coding window. What this does is to
instruct VBA to check your variables for you. Take the following code as an Example:

At the very top of the code we have Option Explicit. The Sub has one variable set up
with the Dim keyword - MyNumber. On the second line, we place a value of 1 in this
variable. On the third line, however, we have this:

MyNumbers = 2

We have accidentally typed MyNumbers instead of MyNumber. If we didn't have


Option Explicit at the top then VBA would have run this code and set up MyNumbers as
a new variable of type As Variant. This could have led to errors further down the code,
if we didn't realise that MyNumber and MyNumbers were two different variables.
Instead, VBA will now not run the code at all. We'll get this error message:
The error message is telling us that there is an undeclared variable somewhere in our
code, a variable not set up with the Dim keyword. (NOTE: There are other keywords
besides Dim that you can start a variable declaration with. We haven't covered these
yet, though.)

So it's a good idea to type Option Explicit at the top of your code window in order to
prevent variables being set up accidentally

LAST ROW & LAST COLUMN FINDING

It is very important to find out the last row and last column of the data. Most of the times we would be
dealing with the data which is not static in terms of the dimensions (number of rows x number of
columns). There are many ways available to find out the last row or column. The best way of capturing
the last row & column number is below:

Last Row:

Sub Find_Last_Row()

Dim Data_LR as Long ‘Used Long Data type assuming that the number of rows are more than 32767.

‘If your data is less, then you can consider Data_LR as Integer

Data_LR=Cells(1048576,1).End(xlUp).Row

‘We might come across version related issues with this syntax as there is no 1048576th row in Excel
Version 2003.

Data_LR=Cells(Rows.Count,1).End(xlUp).Row

‘ Rows.Count returns the number of rows in the sheet. Using this syntax, we can avoid the version
related issues.
End Sub

Sub Find_Last_Column()

Dim Data_LC as Integer ‘ As there are only 16384 columns available and Integer can handle it

Data_LC=Cells(1, Columns.Count).End(xlToLeft).Column

End Sub

LOOPS

What is a Loop?

If, in your VBA program, you need to perform the same task (i.e. repeat the same block of code)
multiple times, this can be done using one of the VBA Loops.

There are 4 types of loops in VBA.

1. For…. Next - Works with number range (Ex: 1 to 10, 200 to 450……)

2. For Each…. Next - Works with collection of objects (Ex: All worksheets in workbook…..)

3. Do While….. Loop - Woks with condition (Ex: As long as a variable value is less than 10….)

4. Do Until…. Loop - Woks with condition (Ex: Until a variable value becomes 10….)

Looping is one of the most powerful programming techniques. A loop in Excel VBA enables you to
loop through a range of cells with just a few codes lines.

Single Loop
You can use a single loop to loop through a one-dimensional range of cells.

Place a command button on your worksheet and add the following code lines:

Dim i As Integer

For i = 1 To 6
Cells(i, 1).Value = 100
Next i
Note: it is good practice to always indent (tab) the code between the words For and Next. This
makes your code easier to read.

Double Loop
You can use a double loop to loop through a two-dimensional range of cells.

Place a command button on your worksheet and add the following code lines:

Dim i As Integer, j As Integer

For i = 1 To 6
For j = 1 To 2
Cells(i, j).Value = 100
Next j
Next i

You might also like