Range, Cells and Offset Property

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Objects & Properties

Dr. Rekha Gupta


Workbook object
• In Excel, a ‘Workbook' is an object that is a part of the ‘Workbooks'
collection. Within a workbook, you have different objects such as
worksheets, chart sheets, cells and ranges, chart objects, shapes, etc.
• With VBA, you can do a lot of stuff with a workbook object – such as
open a specific workbook, save and close workbooks, create new
workbooks, change the workbook properties, etc.
Using Workbook Names

• If you have the exact name of the workbook that you want to refer to, you can use the name in the code.

• Let's begin with a simple example.

• If you have two workbooks open, and you want to activate the workbook with the name – Examples.xlsx, you can
use the below code:

Sub ActivateWorkbook()
Workbooks("Examples.xlsx").Activate
End Sub

• Note that you need to use the file name along with the extension if the file has been saved. If it hasn't been saved,
then you can use the name without the file extension.
Specific cell in a worksheet in a workbook
• If you want to activate a workbook and select a specific cell in a worksheet in that
workbook, you need to give the entire address of the cell (including the Workbook
and the Worksheet name).

Sub ActivateWorkbook()
Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate
Range("A1").Select
End Sub

• The above code first activates Sheet1 in the Examples.xlsx workbook and then
selects cell A1 in the sheet.
Using index numbers

• You can also refer to the workbooks based on their index number.

• For example, if you have three workbooks open, the following code would show you the names of the three workbooks in
a message box (one at a time).

Sub WorkbookName()
MsgBox Workbooks(1).Name
MsgBox Workbooks(2).Name
MsgBox Workbooks(3).Name
End Sub

• The above code uses MsgBox – which is a function that shows a message box with the specified text/value (which is the
workbook name in this case).
Drawback with index numbers
• Excel treats the workbook opened first to have the index number as 1,
and the next one as 2 and so on.

• Despite this drawback, using index numbers can come in handy. For
example, if you want to loop through all the open workbooks and
save all, you can use the index numbers. In this case, since you want
this to happen to all the workbooks, you're not concerned about their
individual index numbers.
Using ActiveWorkbook

• ActiveWorkbook, as the name suggests, refers to the workbook that is active.

• The below code would show you the name of the active workbook.

Sub ActiveWorkbookName()
MsgBox ActiveWorkbook.Name
End Sub

• When you use VBA to activate another workbook, the ActiveWorkbook part in the VBA
after that would start referring to the activated workbook.
• If you have a workbook active and you insert the following code into it and run it, it would
first show the name of the workbook that has the code and then the name of Examples.xlsx
(which gets activated by the code).

Sub ActiveWorkbookName()
MsgBox ActiveWorkbook.Name
Workbooks("Examples.xlsx").Activate
MsgBox ActiveWorkbook.Name
End Sub

• Note that when you create a new workbook using VBA, that newly created workbook
automatically becomes the active workbook.
Creating a New Workbook Object

• The following code will create a new workbook.

Sub CreateNewWorkbook()
Workbooks.Add
End Sub

• When you add a new workbook, it becomes the active workbook.

• The following code will add a new workbook and then show you the name of that workbook (which would be the default Book1 type
name).

Sub CreateNewWorkbook()
Workbooks.Add
MsgBox ActiveWorkbook.Name
End Sub
Open a Workbook using VBA
• You can use VBA to open a specific workbook when you know the file path of the workbook.

• The below code will open the workbook – Examples.xlsx which is in the Documents folder on my system.

Sub OpenWorkbook()
Workbooks.Open ("C:\Users\sumit\Documents\Examples.xlsx")
End Sub

• In case the file exists in the default folder, which is the folder where VBA saves new files by default, then you can just specify the
workbook name – without the entire path.

Sub OpenWorkbook()
Workbooks.Open ("Examples.xlsx")
End Sub

• In case the workbook that you're trying to open doesn't exist, you'll see an error.

• To avoid this error, you can add a few lines to your code to first check whether the file exists or not and if it exists then try to open it.
• The below code would check the file location and if it doesn't exist, it will show a
custom message (not the error message):

• Sub OpenWorkbook()
• If Dir("C:\Users\sumit\Documents\Examples.xlsx") <> "" Then
• Workbooks.Open ("C:\Users\sumit\Documents\Examples.xlsx")
• Else
• MsgBox "The file doesn't exist"
• End If
• End Sub
Saving a Workbook

• To save the active workbook, use the code below:

Sub SaveWorkbook()
ActiveWorkbook.Save
End Sub

• This code works for the workbooks that have already been saved earlier. Also,
since the workbook contains the above macro, if it hasn't been saved as a .xlsm
(or .xls) file, you will lose the macro when you open it next.
If saving for the first time
Default location saving
• The below code would save the active workbook as a .xlsm file in the
default location (which is the document folder in my system).

• Sub SaveWorkbook()
• ActiveWorkbook.SaveAs Filename:="Test.xlsm",
FileFormat:=xlOpenXMLWorkbookMacroEnabled
• End Sub
Specified location
• If you want the file to be saved in a specific location, you need to
mention that in the Filename value. The below code saves the file on
my desktop.

• Sub SaveWorkbook()
• ActiveWorkbook.SaveAs
Filename:="C:\Users\sumit\Desktop\Test.xlsm",
FileFormat:=xlOpenXMLWorkbookMacroEnabled
• End Sub
Saving all Open Workbooks

• If you have more than one workbook open and you want to save all the workbooks, you can use the code
below:

Sub SaveAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
wb.Save
Next wb
End Sub

• The above saves all the workbooks, including the ones that have never been saved. The workbooks that
have not been saved previously would get saved in the default location.
• If you only want to save those workbooks that have previously been saved, you can use
the below code:

Sub SaveAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Path <> "" Then
wb.Save
End If
Next wb
End Sub
Saving and Closing All Workbooks

• If you want to close all the workbooks, except the workbook that has the current code in it, you
can use the code below:

Sub CloseandSaveWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Name <> ThisWorkbook.Name Then
wb.Close SaveChanges:=True
End If
Next wb
End Sub
• Using ThisWorkbook

• ThisWorkbook refers to the workbook where the code is being


executed.

• Every workbook would have a ThisWorkbook object as a part of it


Timestamp n new workbook
• And it also adds a date and timestamp as a part of the workbook name. This can
help you track any mistake you did as you never lose any of the previously created
backups.

Sub CreateaCopyofWorkbook()
ThisWorkbook.SaveCopyAs Filename:="C:\Users\sumit\Desktop\BackupCopy" &
Format(Now(), "dd-mm-yy-hh-mm-ss-AMPM") & ".xlsm"
End Sub

• The above code would create a copy every time you run this macro and add a
date/time stamp to the workbook name.
• Assign Workbook Object to a Variable

• In VBA, you can assign an object to a variable, and then use the
variable to refer to that object.

• For example, in the below code, I use VBA to add a new workbook
and then assign that workbook to the variable wb.
Worksheet
• Represents a worksheet.
• Remarks
• The Worksheet object is a member of the Worksheets collection. The
Worksheets collection contains all the Worksheet objects in a
workbook.
• The Worksheet object is also a member of the Sheets collection. The
Sheets collection contains all the sheets in the workbook (both chart
sheets and worksheets).
Example

• Use Worksheets (index), where index is the worksheet index number or name, to return a single Worksheet object. The following example
hides worksheet one in the active workbook.
Worksheets(1).Visible = False
• The worksheet index number denotes the position of the worksheet on the workbook's tab bar. Worksheets(1) is the first (leftmost)
worksheet in the workbook, and Worksheets(Worksheets.Count) is the last one. All worksheets are included in the index count, even if
they're hidden.
• The worksheet name is shown on the tab for the worksheet. Use the Name property to set or return the worksheet name. The following
example protects the scenarios on Sheet1.
Dim strPassword As String
strPassword = InputBox ("Enter the password for the worksheet")
Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True
• When a worksheet is the active sheet, you can use the ActiveSheet property to refer to it. The following example uses the Activate method
to activate Sheet1, sets the page orientation to landscape mode, and then prints the worksheet.
Worksheets("Sheet1").Activate
ActiveSheet.PageSetup.Orientation = xlLandscape
ActiveSheet.PrintOut
The Range Property

• The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same
argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.
• The following example shows you how to place a value in a cell using the Range property.
Public Sub WriteToCell()

' Write number to cell A1 in sheet1 of this workbook


ThisWorkbook.Worksheets("Sheet1").Range("A1") = 67

' Write text to cell A2 in sheet1 of this workbook


ThisWorkbook.Worksheets("Sheet1").Range("A2") = "John Smith"

' Write date to cell A3 in sheet1 of this workbook


ThisWorkbook.Worksheets("Sheet1").Range("A3") = #11/21/2017#

End Sub
• As you can see Range is a member of the worksheet which in turn is a
member of the Workbook.
• This follows the same hierarchy as in Excel so should be easy to
understand.
• To do something with Range you must first specify the workbook and
worksheet it belongs to.
Using Sheetname directly
Public Sub UsingCodeName()

' Write number to cell A1 in sheet1 of this workbook


Sheet1.Range("A1") = 67

' Write text to cell A2 in sheet1 of this workbook


Sheet1.Range("A2") = "John Smith"

' Write date to cell A3 in sheet1 of this workbook


Sheet1.Range("A3") = #11/21/2017#

End Sub
Writing to a range
Public Sub WriteToMulti()

' Write number to a range of cells


Sheet1.Range("A1:A10") = 67

' Write text to multiple ranges of cells


Sheet1.Range("B2:B5,B7:B9") = "John Smith"

End Sub
• Returns a Range object that represents all the cells on the
worksheet (not just the cells that are currently in use).
• Syntax
• expression . Cells
• expression A variable that represents a Worksheet object.
• Remarks

Cell property • Because the Item property is the default property for the
Range object, you can specify the row and column index
immediately after the Cells keyword. For more information,
see the Item property and the examples for this topic.
• Using this property without an object qualifier returns a
Range object that represents all the cells on the active
worksheet.
• Example
The Cells Property of the Worksheet

• The worksheet object has another property called Cells which is very
similar to range. There are two differences

• Cells returns a range of one cell only.


• Cells takes row and column as arguments.
Example
This example sets the font size for cell C5 on Sheet1 to 14 points.
Worksheets("Sheet1").Cells(5, 3).Font.Size = 14

This example clears the formula in cell one on Sheet1.


Worksheets("Sheet1").Cells(1).ClearContents
This example sets the font and font size for every cell on Sheet1 to 8-point Arial
With
Worksheets("Sheet1").Cells.Font .Name = "Arial" .Size = 8
End With
Using cells and ranges to write to a cell
Public Sub UsingCells()

' Write to A1
Sheet1.Range("A1") = 10
Sheet1.Cells(1, 1) = 10

' Write to A10


Sheet1.Range("A10") = 10
Sheet1.Cells(10, 1) = 10

' Write to E1
Sheet1.Range("E1") = 10
Sheet1.Cells(1, 5) = 10

End Sub
Offset Property of Range

• Range has a property called Offset. The term Offset refers to a count
from the original position. It is used a lot in certain areas of
programming.
• With the Offset property you can get a Range of cells the same size
and a certain distance from the current range. The reason this is
useful is that sometimes you may want to select a Range based on a
certain condition.
Public Sub UsingOffset()

' Write to B2 - no offset


Sheet1.Range("B2").Offset() = "Cell B2"

' Write to C2 - 1 column to the right


Sheet1.Range("B2").Offset(, 1) = "Cell C2"

' Write to B3 - 1 row down


Sheet1.Range("B2").Offset(1) = "Cell B3"

' Write to C3 - 1 column right and 1 row down


Sheet1.Range("B2").Offset(1, 1) = "Cell C3"

' Write to A1 - 1 column left and 1 row up


Sheet1.Range("B2").Offset(-1, -1) = "Cell A1"

' Write to range E3:G13 - 1 column right and 1 row down


Sheet1.Range("D2:F12").Offset(1, 1) = "Cells E3:G13"

End Sub
Reading Values from one Cell to another

• In most of the examples so far we have written values to a cell. We do


this by placing the range on the left of the equals sign and the value
to place in the cell on the right. To write data from one cell to another
we do the same. The destination range goes on the left and the
source range goes on the right.
Example
Public Sub ReadValues()

' Place value from B1 in A1


Sheet1.Range("A1") = Sheet1.Range("B1")

' Place value from B3 in sheet2 to cell A1


Sheet1.Range("A1").Value = Sheet2.Range("B3")

' Place value from B1 in cells A1 to A5


Sheet1.Range("A1:A5") = Sheet1.Range("B1")

' You need to use the "Value" property to read multiple cells
Sheet1.Range("A1:A5") = Sheet1.Range("B1:B5").Value

End Sub
• As you can see from this example it is not possible to read from
multiple cells. If you want to do this you can use the Copy function of
Range with the Destination parameter
Public Sub CopyValues()

' Store the copy range in a variable


Dim rgCopy As Range
Set rgCopy = Sheet1.Range("B1:B5")

' Use this to copy from more than one cell


rgCopy.Copy Destination:=Sheet1.Range("A1:A5")

' You can paste to multiple destinations


rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6")

End Sub
Reading Values to variables

• You can also read from a cell to a variable. A variable is used to store
values while a Macro is running. You normally do this when you want
to manipulate the data before writing it somewhere. The following is
a simple example using a variable. As you can see the value of the
item to the right of the equals is written to the item to the left of the
equals.
Public Sub UseVar()

' Create
Dim val As Integer

' Read number from cell


val = Sheet1.Range("A1")

' Add 1 to value


val = val + 1

' Write new value to cell


Sheet1.Range("A2") = val

End Sub
To read text to a variable you use a variable of type String.

Public Sub UseVarText()

' Declare a variable of type string


Dim sText As String

' Read value from cell


sText = Sheet1.Range("A1")

' Write value to cell


Sheet1.Range("A2") = sText

End Sub
Range of cells
• You can write a variable to a range of cells. You just specify the range on
the left and the value will be written to all cells in the range.

Public Sub VarToMulti()

' Read value from cell


Sheet1.Range("A1:B10") = 66

End Sub
Offset property
• Another useful way to refer to a cell or group of cells is with the Offset
property. This is used with the Range property so that you can specify a
new location. But the new location is based on cells that you specify. As
an example, examine this code:
• Range("A1").Offset(RowOffSet:=1, ColumnOffset:=1).Select
• The above code will select cell B2. The location we've used is cell A1.
We've then typed a dot followed by the word Offset. In between round
brackets, you tell Excel the new location. This is done with the parameters
RowOffSet and ColumnOffSet. (The two are separated by a comma.) In
other words, move one row from cell A1 and one column from cell A1.
Missing values
• You can use a shorthand instead of RowOffSet and ColumnOffSet. The shorthand just uses the numbers:
• Range("A1").Offset(1, 1).Select
• You can also just specify the Rows and not the columns:
• Range("A1").Offset(1).Select
• Here, we've missed off the column parameter and its comma. Excel takes this to mean you want to
move one row down from the cell you specified with Range. The cell selected will now be A2. (We've
gone down a row but stayed in the same column.)
• Similarly, you can specify the columns but not the rows:
• Range("A1").Offset(, 1 ).Select
• Now, the row position is blank and the column position is filled in. Notice that we have left in the
comma, though. Excel takes this to mean that you don't want a new position for the rows, just the
columns. The cell selected will now be B1. (We've gone across one column but stayed in the same row.)
Negative offset
• You can also specify negative numbers:
• Range("B2").Offset(-1, -1 ).Select
• This time, we're starting in cell B2. In between the round brackets of Offset we have -1,
-1. A negative number means go up one row or column from the starting position.
Going up one row and one column from cell B2 takes you to cell A1.
• You can also specify more than one cell for the Range:
• Range("A1:C3").Offset(1, 1).Select
• Here, we've started with the range of cells A1 to C3. We want to offset this entire
range by one row and one column. The new range of cells in the line of code above will
be B2 to D4. When specifying a range of cells with offset, not only does the first cell
(A1 above) get moved across and down 1 but the last cell (C3) gets moved across 1 and
down 1.

You might also like