Vba access excel object

I dissent from both the answers. Don’t create a reference at all, but use late binding:

  Dim objExcelApp As Object
  Dim wb As Object

  Sub Initialize()
    Set objExcelApp = CreateObject("Excel.Application")
  End Sub

  Sub ProcessDataWorkbook()
     Set wb = objExcelApp.Workbooks.Open("path to my workbook")
     Dim ws As Object
     Set ws = wb.Sheets(1)

     ws.Cells(1, 1).Value = "Hello"
     ws.Cells(1, 2).Value = "World"

     'Close the workbook
     wb.Close
     Set wb = Nothing
  End Sub

You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().

This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there’s a different version of Excel installed, or if it’s installed in a different location.

Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.

Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods

————————————————————————————

Contents:

VBA Objects

The Excel Object Model

Active Object

Access an Object / Access a Single Object from its Collection

Properties and Methods of Objects

Working with Objects in Excel VBA

————————————————————————————

An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object, a Method is an action performed by an object. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. An object is a thing which contains data and has properties and methods. To manipulate an Object you will Set its Properties and Call its Methods.

For more articles related to Excel VBA objects: Excel VBA Application Object, the Default Object in Excel; Excel VBA Workbook Object, working with Workbooks in Excel; Microsoft Excel VBA — Worksheets; Excel VBA Range Object, Referencing Cells and Ranges; Excel VBA Custom Classes and Objects.

Visual Basic is not truly an Object-Orientated Programming (OOP) Language

Visual Basic (Visual Basic 6) is not truly an Object-Orientated Programming (OOP) Language whereas its successor Visual Basic.NET (part of the .NET platform) is a full-fledged Object Oriented programming language meeting the criteria of encapsulation, inheritance and polymorphism, where everything in Visual Basic.NET can be treated as an object. Visual Basic has many (but not all) elements of an Object-Orientated Programming (OOP) language. VBA deals with objects but is not truly an Object-Orientated Programming language.

VBA Objects

An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object (like name, color, size) or define an object’s behaviour (viz. if visible or enabled). An object’s data or information can be accessed with properties (viz. Value property, Name property). A Method is an action performed by an object. Calling a Method will execute a vba code which will cause the object to perform an action. You can associate objects with nouns, properties with adjectives and methods with verbs. An object could be a house, car, table or pen. Properties of a car include its color or size, which describe it. A car can perform actions of moving, accelerating or turning which are its methods. Examples of objects in Excel are workbook, worksheet, range, command button, font, etc. A Range object has «Value» as one of its properties and «Select» as one of its methods. Similarly a worksheet has, among others, a «Name» property, a «Delete» method, and a «Copy» method having arguments which contain information in respect of the worksheet to be copied.

Objects also have event procedures attached to them. Events are actions performed, or occurrences, which trigger a VBA code or macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. Excel provided built-in event procedure — an Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls.  Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». In the Worksheet Change event procedure, the Worksheet object is associated with the Change event, which means that with the worksheet change event, a sub-procedure containing customized code runs automatically when you change the contents of a worksheet cell. Custom Events — you can also define your own events in custom classes (class modules), and create event procedures that run when those events occur.

A Collection Object in vba refers to a group of related items, as a single object. Many objects are present both in single form as well as in multiples. For example: (i) Workbook & Workbooks — all open Workbook objects in Excel are referred to as the Workbooks collection; (ii) Worksheet & Worksheets — A Worksheets Collection object refers to all Worksheets contained in a workbook. All elements (items) of a collection share the same properties and methods, though they do not need to be of the same data type. You can either create your own collection using the vba Collection class or use the Excel VBA built-in collections such as Worksheets (the Worksheets Collection Object includes all Worksheets in a workbook). With a Collection Object you can work with all objects (which are its elements) as a group as against working with a single object. The basic ways of working with elements of a collection include: adding an element using the Add method, removing an element using the Remove method, determining the number of elements contained in a collection using the Count property, accessing a specific element using the Item property, enumerate each element of a collection using the For Each…Next Statement, and so on.

The Excel Object Model

All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. When you use vba in an Office Application, say PowerPoint, a reference to the PowerPoint Object Library is set by default. When you Automate to work with PowerPoint objects from another application, say Excel, you can add a reference to the PowerPoint object library in Excel (your host application) by clicking Tools-References in VBE, which will enable using PowerPoint’s predefined constants — the PowerPoint objects, properties, and methods will appear in the Object Browser and the syntax will be checked at compile time.

All objects, and their associated Properties and Methods, available in Excel VBA can be viewed in the Object Browser in the VBE code window — in VBE click on View>Object Browser or press F2. On the top-left of the window is the Project/Library box, which by default mentions <All Libraries>, wherein you can choose Excel from the list to view all Excel objects. On the left pane of the window the available Classes (Objects) are listed, and on the right pane are displayed all Members (ie. properties, methods, events & constants) associated with the selected object in the Classes list. Global members (ie. properties, methods, events & constants) are those in respect of which the object name can be omitted. In the Excel Object Library, those properties and methods whose use does not require specifying the Application object qualifier are considered «global». Refer Image 1 to view the Object Browser.

The Object Model of the Application (Excel) refers to and contains its programming objects which are related to each other in a hierarchy. The entire Excel application is represented by the Application Object which is at the top of the Excel object hierarchy and moving down you can access the objects from Application to Workbook to Worksheet to Range (Cells) and further on, by connecting the objects with a period (dot). Excel objects are accessed through ‘parent’ objects — Worksheet is the parent of the Range Object, and the Workbook is the parent of the Worksheet object, and the Application object is the parent of the Workbook object.

Example — Start at the top of the hierarchy with the Application object, then move down to the workbook, worksheet, range and font objects, as follows:

Application.ActiveWorkbook.Worksheets(1).Range(«A1»).Font

The Excel Object Model hierarchy — the most used objects:

The Application Object refers to the host application of Excel, and the entire Excel application is represented by it. The Workbook Object, appears next below the Application Object in Excel object hierarchy, and represents a single workbook within the Excel application. A workbook is also referred to as an Excel file. The Workbooks Collection Object includes all currently open Workbooks in Excel. The Worksheet Object, appears next below the Workbook Object in Excel object hierarchy, and represents a single worksheet within the workbook. The Worksheets Collection Object includes all Worksheets in a workbook. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells (when the Range is a union of multiple blocks of cells it is referred as a non-contiguous range of cells). The Range object is usually used maximum within the Excel application.

The Application object is the Default Object, Excel assumes it even when it is not specified. The Application qualifier is mostly not required to be used in vba code, because the default application is Excel itself, unless you want to refer to other outside applications (like Microsoft Word or Access) in your code or you want to refer to Excel from another application like Microsoft Word. In your VBA code, both the expressions Application.ActiveWorkbook.Name and ActiveWorkbook.Name will have the same effect of returning the Active Workbook’s name. However, there are some instances when the Application qualifier is required to be used, viz. generally when using properties & methods which relate to the Excel window’s appearance, or which relate to how the excel application behaves as a whole.

The Active Object

If no Workbook or Worksheet is specified, Excel refers to the current Active Workbook or Worksheet by default. In your vba code you can also refer the current Active Workbook or Sheet as ActiveWorkbook or ActiveSheet. Both the expressions Worksheets(1).Name and ActiveWorkbook.Worksheets(1).Name will return the name of the first worksheet in the Active Workbook which also becomes the default object in this case. Similarly, both the expressions Range(«A1»).Value = 56 and ActiveSheet.Range(«A1»).Value = 56 will enter the value 56 in cell A1 of the Active Worksheet in the Active Workbook. This is a general rule that omitting reference to a Workbook or Worksheet refers to the current Active Workbook or Worksheet by default, but this rule is subject to below conditions.

Note: (i) omitting reference to a Worksheet when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, …) will reference the specific sheet in whose module your code is entered and NOT the Active Sheet; and (ii) omitting reference to a Workbook when your vba code is entered in the Workbook module (ThisWorkbook) will reference the workbook in which your code is entered and NOT the Active Workbook. This means: (i) omitting reference to a Worksheet will default to ActiveSheet when your vba code is entered in Standard Code Modules (Module1, Module2, …) or the Workbook module (ThisWorkbook) and NOT when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, …) or UserForms or any Class modules you create; and (ii) omitting reference to a Workbook will default to ActiveWorkbook when your vba code is entered in Standard Code Modules (Module1, Module2, …) or in the Sheet Modules (viz. Sheet1, Sheet2, …) and NOT when your vba code is entered in the Workbook module (ThisWorkbook).

Access an Object / Access a Single Object from its Collection

Access a Workbook Object

Workbook Object and Workbooks Collection: All open Workbook objects in Excel are referred to as the Workbooks collection. You can access a single Workbook from the Workbooks Collection by using the workbook index. This index is either the workbook name or an index number, and is used as Workbooks(index). To activate a workbook named «VbaProject», use Workbooks(«VbaProject»).Activate. To activate the first workbook, use Workbooks(1).Activate. The index number starts at 1, which indicates the first workbook which is created or opened, and the last workbook number will be returned by Workbooks.Count (which counts the number of open workbooks). The activate the second workbook use Workbooks(2).Activate, to activate the last workbook use Workbooks(Workbooks.Count).Activate.

Access a Worksheet Object

Worksheet Object and Worksheets Collection: A Worksheets Collection object refers to all Worksheets contained in a workbook. Similar to a Workbook object, you can access a single Worksheet from the Worksheets Collection by using the worksheet index. The index can be the worksheet name or an index number, and is used as Worksheets(index). To activate a worksheet named «Sheet1», use Worksheets(«Sheet1»).Activate. To activate the first worksheet, use Worksheets(1).Activate. The index number starts at 1, which indicates the first worksheet, and the last worksheet number will be returned by Worksheets.Count (which counts the number of worksheets in a workbook). The activate the second worksheet use Worksheets(2).Activate, to activate the last worksheet use Worksheets(Worksheets.Count).Activate.

Access a Sheet Object

Sheet Object and Sheets Collection: A Sheets Collection object refers to all sheets contained in a workbook, which includes chart sheets and worksheets. You can access a single Sheet from the Sheets Collection by using the sheet index viz. Sheets(index), similar to accessing a Worksheet. The Sheet index can be the sheet name viz. Sheets(«Sheet1»).Activate, or index number viz. Sheets(1).Activate or Sheets(Sheets.Count).Activate.

Access a Range Object

A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. You can refer to a range by using the following expressions.

Referencing a single cell:

Enter the value 10 in the cell A1 of the worksheet named «Sheet1»:

Worksheets(«Sheet1»).Range(«A1»).Value = 10

Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:

ActiveSheet.Cells(2, 3).Value = 10

Referencing a range of cells:

Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:

ActiveSheet.Range(«A1:B3»).Value = 10

ActiveSheet.Range(«A1», «B3»).Value = 10

ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10

Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Range(«A1,B3»).Value = 10

Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:

ActiveWorkbook.Worksheets(«Sheet3»).Range(«B2:D3,H7»).Interior.Color = vbRed

Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:

Range(«Score»).Value = 10

ActiveSheet.Range(«Score»).Value = 10

Select all the cells of the active worksheet:

ActiveSheet.Cells.Select

Cells.Select

Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:

ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»

ActiveSheet.Cells.Font.Size = 11

Cells.Font.Size = 11

Referencing Row(s) or Column(s):

Select all the Rows of active worksheet:

ActiveSheet.Rows.Select

Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Rows(2).Value = 10

Select all the Columns of the active worksheet:

ActiveSheet.Columns.Select

Columns.Select

Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:

ActiveSheet.Columns(3).Value = 10

Columns(«C»).Value = 10

Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Columns(«A:C»).Value = 10

Relative Referencing:

Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«A1») = 10

Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«B2») = 10

Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:

Range(«C5»).Offset(1, 2) = 10

Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:

Range(«C5:E8»).Offset(2, 3) = 10

Properties and Methods of Objects

As explained above, to manipulate an Object you can Set its Properties and Call its Methods.

To access the property of an object, connect the Object Name to the Property by inserting a period (full stop or dot) between them viz. Worksheets(1).Name, returns the name of the first worksheet. Some objects have default properties viz. a Range object’s default property is Value and you can omit to mention Value. In this case using Range(«A1»).Value or only  Range(«A1») is the same and will return the value or content of the Cell A1, and the expressions can be used alternatively. Properties can be: (i) a Read-only property, which means you can read or access but cannot change it; or (ii) a Read-write property, in which case your VBA code can both read or change value.

To access the method of an object, connect the Object Name to the Method by inserting a period (full stop or dot) between them viz. Worksheets(1).Activate, activates the first worksheet by calling the Activate method. A Method may or may not have argument(s). An argument is a value supplied to a method to enable it to perform an action. To use the Calculate & Activate Method on a Worksheet object, you need not supply an argument viz. Worksheets(«Sheet1»).Calculate or Worksheets(«Sheet1»).Activate. To use the Add Method on a Worksheets Collection Object, you need to supply multiple arguments.

An Object’s Method is a procedure that acts on it. A Method can have Arguments which are required to be specified and/or it can have Optional Arguments which you can omit to specify. Arguments which are displayed in square brackets in the method’s syntax, are optional while others are required. The arguments can be supplied in the order of the position in which they are defined in the method syntax, each argument value being separated with a comma even for optional arguments which may not be specified. Alternatively the arguments can be supplied by the argument name (referred as named arguments) in which case the position in which they are specified becomes irrelevant. Each Named argument will also be separated with a comma, but not for optional arguments which are not specified. While specifying named arguments, you specify the argument name followed by a colon and an equal sign (:=) which is followed by the argument value, viz. ArgumentName:= «ArgumentValue». Using named arguments will facilitate keeping a track of the arguments which have been specified and those which have been omitted.

Examples of using an Object’s Method:

The Activate Method applied to a Worksheet Object, activates the specified worksheet and makes it current. This method has no argument(s).

Worksheets(«Sheet1»).Activate

The Add Method applied to a Worksheets Collection Object, creates a new worksheet. It has multiple arguments, all of which are Optional. Syntax: Worksheets.Add(Before, After, Count, Type).

Using the Add Method without specifying any argument — adds a new worksheet before the Active Worksheet because both the Before & After arguments are omitted (note that the default value of Count argument is 1):

Worksheets.Add

Using the Add Method specifying one named argument of After — adds a new worksheet after the Worksheet named «Sheet2» (note that the default value of Count argument is 1):

Worksheets.Add After:=Worksheets(«Sheet2»)

Using the Add Method specifying two named arguments of After & Count — adds 3 new worksheets after the Worksheet named «Sheet2»:

Worksheets.Add After:=Worksheets(«Sheet2»), Count:=3

Using the Add Method specifying two positional arguments of After & Count — adds 2 new worksheets after the Worksheet named «Sheet2»:

Worksheets.Add , Worksheets(«Sheet2»), 2

Using the Add Method specifying two positional arguments of Before & Count — adds 2 new worksheets before the Worksheet named «Sheet2»:

Worksheets.Add Worksheets(«Sheet2»), , 2

Using the Add Method specifying one named argument of Before — adds a new worksheet before the Worksheet named «Sheet2», and using the Name property, names the new worksheet «NewSheet»:

Worksheets.Add(Before:=Worksheets(«Sheet2»)).Name = «NewSheet»

Working with Objects in Excel VBA

Excel VBA IntelliSense

While writing vba code, when you type an Object followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense). Ensure that the Excel VBA IntelliSense is turned on: in VBE, Tools>Options>Editor, ‘Auto List Members’ should be selected/checked. For instance, the IntelliSense will pop up after you type range followed by a period viz. range.[Intellisense for a Range object Pops Up]. Refer Image 2 — properties of the Range object are indicated by the fingers and methods of the Range object are indicated by the green boxes/bricks. You can either type or else select from this pop-up list, the method or property you want to connect with the object.

Using With…End With Statement to refer to Objects

As explained earlier, to access an Object and its properties & methods, you have to use the object name. In your vba code you will often need to refer to an object multiple times, and each time you will have to use its name. Instead of using the object name every time, you can execute multiple code lines which repeatedly refer to an object, by using the With…End With Statement. You start the block with the first line as:- type the With keyword followed by the Object Name. Insert one or more code lines after the first line:- access the object’s members (its properties, methods, etc) by typing a period (dot) followed by the property or method name, and you need not specify the object name each time. Terminate the block with the end line:- «End With». Refer to the below example, which shows how to make your vba code more readible using a With Block, and with Nesting ie. Block within a Block:

‘use the With … End With statement to refer to a Range object
With Worksheets(«Sheet1»).Range(«A1»)

‘use the Value property of the Range object, to set the value for the range:
.Value = 11
‘use the Name property, of the Range object, to set the range name:
.Name = «Score»

‘use the Font Property of the Range object that returns a Font object, and then use the With … End With statement to refer to the Font object
With .Font

‘note that because you are using the With … End With statement to refer to the Font object within the Range object, you will not refer to both the range or font objects below:
‘use the Name property of the Font object to set the font name:
.Name = «Arial»
‘use the Bold property of the Font object to set the font to bold:
.Bold = True
‘use the Color property of the Font object to set the font color:

.Color = vbRed

‘use the Borders property of the Range object to return all four borders (Borders collection object), and then use the LineStyle property of the Borders object to add a double border:
.Borders.LineStyle = xlDouble

‘the Clear Method of the Range object, clears the range (clears the contents, formulas and formatting):

End With

Using Variables in VBA

A variable is a named storage location used to store temporary values or information for use in execution of the code. In your vba program, a variable stores data and its content is used or changed later while executing the code. By declaring a variable for use in your code, you tell the Visual Basic compiler the variable’s data type (type of value it represents viz. integer, decimal, text, boolean, etc.) and other information such as its scope/level (what code can access it — variables can be Procedure Level, Module Level or can have a Public scope). Variables must be explicitly declared using the Dim, Private, Public, ReDim, or Static statements. When you declare variables by using a Dim statement (Dim is short for dimension): for declaring a variable to hold an Integer value, use «Dim rowNumber As Integer»; for declaring a variable to hold text values, use «Dim strEmployeeName As String»; and so on.

Keywords in VBA

Keywords are reserved words that VBA uses as part of its programming language. Keywords are words or commands that are recognized by VBA and can be used in vba code only as part of the vba language (like in a statement, function name, or operator) and not otherwise (like sub-procedure or variable names). Examples of keywords are: Sub, End, Dim, If, Next, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, and so on. To get help on a particular keyword, insert your mouse cursor within the keyword (in your vba code in VBE ) and press F1. Note that Keywords get capitalized in the vba code indicating that they have been written correctly viz. typing next will automatically appear as Next.

Assign an Object to a Variable, using the Set Keyword

In VBA, you use the Set keyword to assign an object reference. To assign an object to a variable in your vba code, you need to use the Set keyword as shown below. Note that using the Dim, Private or Public statements you only declare a variable as to its data type (type of value it represents viz. integer, text, etc.) and other information such as its scope/level (what code can access it). The actual object is assigned or referred to it only by using the Set statement. It is shorter to use an object variable & also more convenient because its data type will be known by VBA so that when you type the variable followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense).

Example: With the following code, we declare a variable (myRange) of Range data type, and then assign the Range object to this variable using the Set keyword, so that every time you want to refer to the specific Range, you can do so by using the variable. The following will enter the value 10 in cells A1 to C3 in the worksheet named «Sheet1».

Dim myRange As Range

Set myRange = Worksheets(«Sheet1»).Range(«A1:C3»)
myRange.Value = 10

What are Excel Objects?

The Excel objects belong to the entities that make
up an Excel Workbook, Worksheets, Columns, Rows, Cell Ranges, etc. Each object
in Excel has loads of Properties that are stored as a part of that object. For example,
an Excel Worksheet’s properties include the Worksheet’s Name, Protection,
Visible Property, Scroll Area, etc., The primary benefit of an object is that
it hides the implementation details. When an item is added, it must allocate
memory, add the item, update the item count, and soon.

Although VBA is not a truly object-oriented
programming language, it does deal with a project. VBA object has specific
functions, properties, and can contain data or child objects. Therefore, if,
during the execution of a macro, we wanted to hide an Excel worksheet, we could
do this by accessing the Worksheet object and altering the ‘Visible’ property.

VBA has a particular type of object, called a
Collection. The Collection, as the name suggests, refers to a group (or collection)
of Excel objects. For example, the ‘Rows’ collection is an object containing
all the rows of a Worksheet.

Object Components

The following are essential components of an object.

1. Property–Allows
us to read a value from the object or write a value to the project.

2.Method–They
are used to some action to do with the object data.

3.Event–Events
occur when a code is executed.

A Real World Analogy

Take an example of House. House is an Object, And
Windows and Doors are its’ child objects. Colors, Height, Floors are properties
of House, and they also have some Events, such as Door Open, Door Close, etc.
Likewise, An Excel worksheet is an object, and a Range of Cells in the
worksheet are child objects of the worksheet. A Worksheet contains several Properties,
Methods, and Events.

Accessing Excel
Objects

The significant Excel Objects can all be accessed
(directly or indirectly) from the ‘Workbooks’ object, which is a collection of
all the currently open Workbooks. Each ‘Workbook’ object contains the ‘Sheets’
object which consists of all the Worksheets and Chart sheets in the Workbook,
and in turn, each ‘Worksheet’ object contains a ‘Rows’ object which further
consists of all Rows in the Worksheet and a ‘Columns’ object including of all
Columns in the Worksheet.

The following are the lists of some
of the more commonly used Excel objects.

  1. Properties: All Objects are accessed via
    Properties. When using Workbook, Workbooks are the property of the Application
    (Object). For example, the Workbook object has the properties ‘Name’, ‘Revision
    Number’, ‘Sheets’, and many more. In the above example, a Range Object is
    having properties like Value, Wrap Text, etc … If, during the execution of a
    VBA macro, the user wanted to hide an Excel worksheet, he could do this by
    accessing the Worksheet object, and adjusting the ‘Visible’ property.

Objective:
Assign the current active Workbook name to the variable vbSheetName, and
displaying the value in A1 cell with wraptext property, and we could use the
following code:

Program

Sub Example()
Dim wbSheetName As String
wbSheetName  = ActiveWorkbook.Name
Range(“A1”).Value= wbSheetName 
Range(“A1”).WrapText= True
End Sub 
Accessing Excel Objects
  • Methods: The action (functions or subs) that
    can be performed on an Object. VBA methods perform specific actions. Object
    methods are procedures that are connected to a certain object type. For
    example, the Workbook object has the methods ‘Activate’, ‘Save’, ‘Close’, and a
    lot more.

Objective: Write “Hello World! ” in cell A1 and select and copy the
selection and paste it in “A1: A10”, cells, respectively.

Program

Sub Method_Macro()
Range("A1").Select
Selection.Copy
Range("A1:A10").Select
ActiveSheet.Paste
End Sub 

Output

VBA methods
  • Application: Excel VBA
    Application Object is one of the frequently used objects which helps in
    automating any task with VBA. It is used to refer to different Excel
    applications and perform various operations on Excel Workbooks. It represents
    the current excel application.

Objective: Run a code where the font of the
active cell of the application is bold.

Program

Sub Application_Macro()
Range("A1").Value = "Hello World"
Application.ActiveCell.Font.Bold = True
End Sub 

Output

Excel VBA Application

  • Workbooks: Workbooks are one of the most common
    Excel objects. Whatever you do in Excel takes place in a workbook, which is
    stored in a file that, by default, has an XLSX extension. An Excel workbook can
    hold any number of sheets (limited only by memory). A Workbook object can be
    accessed from the Workbooks Collection by using a Workbook index number or a
    Workbook name.

There are four types of sheets in VBA which
are as follows:

  • Worksheets
  • Excel 4.0 XLM macrosheet. It has become obsolete
    but is still supported in various industries.
  • Chart sheets
  • Excel 5.0 dialog sheet (obsolete, but still
    supported)

The user can use ‘ActiveWorkbook’ to
access the current active Workbook or can also access the Worksheets object,
which is a collection of all the Worksheets in the Workbook.

Objective: Print the active workbook name in
the A1 cell.

Program

Sub Workbook_Example()
Dim wbSheetName As String
wbSheetName  = ActiveWorkbook.Name
Range(“A1”).Value= wbSheetName 
End Sub 

Output

Print the active workbook name
  • Worksheets: When it comes to think of
    a spreadsheet, the most common type of sheet is a worksheet. Worksheets contain
    cells, and the cells store data and formulas. A worksheet cell can hold a
    constant value– a number, text, a date/time, a Boolean value (True or False),
    or the result of a function/formula. The user can also use ‘ActiveSheet’ to access the
    current active Sheet.

Objective: Print the active sheet
name in the A1 cell.

Program

Sub Worksheet_Macro()
Dim wsSheetName As String
wsSheetName = ActiveSheet.Name
Range("A1").Value = wsSheetName
Range("A1").WrapText = True
End Sub 

Output

Print the active sheet name in the A1 cell
  • Range : The range is another most
    frequently used object when automating tasks with VBA. A Range object can refer
    to different Ranges in Excel Worksheets and can perform a different task.  

A range can be specified by either a cell
range with particular start and end cell (e.g. Range(«A1:A10») or
Range(«A1», «A10») or Range(Cells(1,10), Cells(1,210)).

Objective: Select the value of range
A1 and paste it in the cells A1: A10 by using Range object.

Program

Sub Range_Macro()
Range("A1").Select
Selection.Copy
Range("A1:A10").Select
ActiveSheet.Paste
End Sub 

Output

Select the value of range A1 and paste it
  • Variable & Constant:
    A variable is used to accommodate a wide variety of data types -from simple
    Boolean values (True or False) to large, double-precision values. Whereas
    constant refers to a named memory location used to hold a value that CANNOT be
    changed during the script execution. If a user tries to change a Constant
    value, the script execution ends up with an error. Constants are declared the
    same way the variable are declared

Rules for declaring variables or constant variables

  • Alphabetic characters, numbers, and some
    punctuation characters, are used but the first character must be alphabetic.
  • Space or periods are not recommended and used.
    Instead, use underscore character.
  • Special characters ($, #, %, & or !) are also
    not allowed in a variable name.
  • Variable names can be as long as 254 characters
    –but using such a long name isn’t suggested.
  • Data Types: It refers to how data is
    stored in memory —as integers, real numbers, strings, and so on. Although VBA
    takes care of data typing automatically, it does so at a cost: slower execution
    and less efficient use of memory and when running large or complex codes can
    present problems when VBA itself handles data types.
Data
Type
Bytes Range
Byte 1
byte
0
to 255
Boolean 2
bytes
True,
False
Integer 2
bytes
-32768
to 32767
Long 4
bytes
-2147483648
to 2147483647
Single 4
bytes
3.402823E38
to –1.401298E-45 (for negative values); 1.401298E-45 to 3.402823E38 (for
positive values)
 
Double 8
bytes
–1.79769313486232E308
to –4.94065645841247E-324 (negative values) and
4.94065645841247E-324
to 1.79769313486232E308 (positive values)
 
 
 
Currency 8
bytes
922,337,203,685,477.5808 to 922,337,203,685,477.5807
 
Decimal 12
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
 
Date 8
bytes
January
1, 0100 to December 31, 9999
 
String
(variable length)
10
bytes + String length
0
to approximately 2 billion characters
 
String
(fixed length)
Length
of string
1
to approximately 65,400 characters
 
Variant
(with numbers)
16
bytes
Any
numeric value up to the range of a double data type. It can also hold special
values, such as Empty, Error, Nothing, and Null.
 
Variant
(with characters)
22
bytes + string length
0
to approximately 2 billion
 
User-defined Varies Varies
by element
 

This tutorial will cover the ways to import data from Excel into an Access Table and ways to export Access objects (Queries, Reports, Tables, or Forms) to Excel.

Import Excel File Into Access

To import an Excel file to Access, use the acImport option of DoCmd.TransferSpreadsheet :

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Table1", "C:TempBook1.xlsx", True

Or you can use DoCmd.TransferText to import a CSV file:

DoCmd.TransferText acLinkDelim, , "Table1", "C:TempBook1.xlsx", True

Import Excel to Access Function

This function can be used to import an Excel file or CSV file into an Access Table:

Public Function ImportFile(Filename As String, HasFieldNames As Boolean, TableName As String) As Boolean
' Example usage: call ImportFile ("Select an Excel File",  "Excel Files", "*.xlsx",  "C:" , True,True, "ExcelImportTest", True, True,false,True)

    On Error GoTo err_handler
  
    If (Right(Filename, 3) = "xls") Or ((Right(Filename, 4) = "xlsx")) Then
                DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, TableName, Filename, blnHasFieldNames
            End If
    If (Right(Filename, 3) = "csv") Then
                DoCmd.TransferText acLinkDelim, , TableName, Filename, True
    End If
    
Exit_Thing:

    'Clean up
    'Check if our linked in Excel table already exists... and delete it if so
    If ObjectExists("Table", TableName) = True Then DropTable (TableName)
    Set colWorksheets = Nothing

    Exit Function
    
err_handler:
    If (Err.Number = 3086 Or Err.Number = 3274 Or Err.Number = 3073) And errCount < 3 Then
        errCount = errCount + 1

    ElseIf Err.Number = 3127 Then
        MsgBox "The fields in all the tabs are the same. Please make sure that each sheet has the exact column names if you wish to import mulitple", vbCritical, "MultiSheets not identical"
        ImportFile = False
        GoTo Exit_Thing
    Else
        MsgBox Err.Number & " - " & Err.Description
        ImportFile = False
        GoTo Exit_Thing
        Resume
    End If
End Function

You can call the function like this:

Private Sub ImportFile_Example()
 Call VBA_Access_ImportExport.ImportFile("C:TempBook1.xlsx", True, "Imported_Table_1")
End Sub

Access VBA Export to New Excel File

To export an Access object to a new Excel file, use the DoCmd.OutputTo method or the DoCmd.TransferSpreadsheet method:

Export Query to Excel

This line of VBA code will export a Query to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputQuery, "Query1", acFormatXLSX, "c:tempExportedQuery.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Query1", "c:tempExportedQuery.xls", True

Note: This code exports to XLSX format. Instead you can update the arguments to export to a CSV or XLS file format instead (ex. acFormatXLSX to acFormatXLS).

Export Report to Excel

This line of code will export a Report to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputReport, "Report1", acFormatXLSX, "c:tempExportedReport.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Report1", "c:tempExportedReport.xls", True

Export Table to Excel

This line of code will export a Table to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputTable, "Table1", acFormatXLSX, "c:tempExportedTable.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Table1", "c:tempExportedTable.xls", True

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Export Form to Excel

This line of code will export a Form to Excel using DoCmd.OutputTo:

DoCmd.OutputTo acOutputForm, "Form1", acFormatXLSX, "c:tempExportedForm.xls"

Or you can use the DoCmd.TransferSpreadsheet method instead:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, "Form1", "c:tempExportedForm.xls", True

Export to Excel Functions

These one line commands work great to export to a new Excel file. However, they will not be able to export into an existing workbook.  In the section below we introduce functions that allow you to append your export to an existing Excel file.

Below that, we’ve included some additional functions to export to new Excel files, including error handling and more.

Export to Existing Excel File

The above code examples work great to export Access objects to a new Excel file.  However, they will not be able to export into an existing workbook.

To export Access objects to an existing Excel workbook we’ve created the following function:

Public Function AppendToExcel(strObjectType As String, strObjectName As String, strSheetName As String, strFileName As String)

    Dim rst As DAO.Recordset
    Dim ApXL As Excel.Application
    Dim xlWBk As Excel.Workbook
    Dim xlWSh As Excel.Worksheet
    Dim intCount As Integer
    Const xlToRight As Long = -4161
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
    Const xlContinuous As Long = 1
      
    Select Case strObjectType

    Case "Table", "Query"
        Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
    Case "Form"
        Set rst = Forms(strObjectName).RecordsetClone
    Case "Report"
        Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
    End Select

    If rst.RecordCount = 0 Then
        MsgBox "No records to be exported.", vbInformation, GetDBTitle
    Else
        On Error Resume Next
        Set ApXL = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Set ApXL = CreateObject("Excel.Application")
        End If
        Err.Clear

        ApXL.Visible = False
        
        Set xlWBk = ApXL.Workbooks.Open(strFileName)
        Set xlWSh = xlWBk.Sheets.Add
        xlWSh.Name = Left(strSheetName, 31)

        
        xlWSh.Range("A1").Select
        Do Until intCount = rst.fields.Count
            ApXL.ActiveCell = rst.fields(intCount).Name
            ApXL.ActiveCell.Offset(0, 1).Select
            intCount = intCount + 1
        Loop

        rst.MoveFirst
        
        xlWSh.Range("A2").CopyFromRecordset rst

        With ApXL
            .Range("A1").Select
            .Range(.Selection, .Selection.End(xlToRight)).Select
            .Selection.Interior.Pattern = xlSolid
            .Selection.Interior.PatternColorIndex = xlAutomatic
            .Selection.Interior.TintAndShade = -0.25
            .Selection.Interior.PatternTintAndShade = 0
            .Selection.Borders.LineStyle = xlNone
            .Selection.AutoFilter
            .Cells.EntireColumn.AutoFit
            .Cells.EntireRow.AutoFit
            .Range("B2").Select
            .ActiveWindow.FreezePanes = True
            .ActiveSheet.Cells.Select
            .ActiveSheet.Cells.WrapText = False
            .ActiveSheet.Cells.EntireColumn.AutoFit
            xlWSh.Range("A1").Select
            .Visible = True
        End With

        'xlWB.Close True
        'Set xlWB = Nothing
        'ApXL.Quit
        'Set ApXL = Nothing
    End If
End Function

You can use the function like this:

Private Sub AppendToExcel_Example()
    Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet", "C:TempTest.xlsx")
End Sub

Notice you are asked to define:

  • What to Output? Table, Report, Query, or Form
  • Object Name
  • Output Sheet Name
  • Output File Path and Name.

VBA Programming | Code Generator does work for you!

Export SQL Query to Excel

Instead you can export an SQL query to Excel using a similar function:

Public Function AppendToExcelSQLStatemet(strsql As String, strSheetName As String, strFileName As String)
    Dim strQueryName As String
    Dim ApXL As Excel.Application
    Dim xlWBk As Excel.Workbook
    Dim xlWSh As Excel.Worksheet
    Dim intCount As Integer
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
    Const xlVAlignCenter = -4108
    Const xlContinuous As Long = 1
    Dim qdf As DAO.QueryDef
    Dim rst As DAO.Recordset
    
    strQueryName = "tmpQueryToExportToExcel"

    If ObjectExists("Query", strQueryName) Then
        CurrentDb.QueryDefs.Delete strQueryName
    End If
    Set qdf = CurrentDb.CreateQueryDef(strQueryName, strsql)
    Set rst = CurrentDb.OpenRecordset(strQueryName, dbOpenDynaset)

    If rst.RecordCount = 0 Then
        MsgBox "No records to be exported.", vbInformation, GetDBTitle
    Else
        On Error Resume Next
        Set ApXL = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Set ApXL = CreateObject("Excel.Application")
        End If
        Err.Clear

        ApXL.Visible = False
        
        Set xlWBk = ApXL.Workbooks.Open(strFileName)
        Set xlWSh = xlWBk.Sheets.Add
        xlWSh.Name = Left(strSheetName, 31)

        
        xlWSh.Range("A1").Select
        Do Until intCount = rst.fields.Count
            ApXL.ActiveCell = rst.fields(intCount).Name
            ApXL.ActiveCell.Offset(0, 1).Select
            intCount = intCount + 1
        Loop

        rst.MoveFirst
        
        xlWSh.Range("A2").CopyFromRecordset rst

        With ApXL
            .Range("A1").Select
            .Range(.Selection, .Selection.End(xlToRight)).Select
            .Selection.Interior.Pattern = xlSolid
            .Selection.Interior.PatternColorIndex = xlAutomatic
            .Selection.Interior.TintAndShade = -0.25
            .Selection.Interior.PatternTintAndShade = 0
            .Selection.Borders.LineStyle = xlNone
            .Selection.AutoFilter
            .Cells.EntireColumn.AutoFit
            .Cells.EntireRow.AutoFit
            .Range("B2").Select
            .ActiveWindow.FreezePanes = True
            .ActiveSheet.Cells.Select
            .ActiveSheet.Cells.WrapText = False
            .ActiveSheet.Cells.EntireColumn.AutoFit
            xlWSh.Range("A1").Select
            .Visible = True
        End With


        'xlWB.Close True
        'Set xlWB = Nothing
        'ApXL.Quit
        'Set ApXL = Nothing
    End If
End Function

Called like this:

Private Sub AppendToExcelSQLStatemet_Example()
    Call VBA_Access_ImportExport.ExportToExcel("SELECT * FROM Table1", "VBASheet", "C:TempTest.xlsx")
End Sub

Where you are asked to input:

  • SQL Query
  • Output Sheet Name
  • Output File Path and Name.

Function to Export to New Excel File

These functions allow you to export Access objects to a new Excel workbook. You might find them more useful than the simple single lines at the top of the document.

Public Function ExportToExcel(strObjectType As String, strObjectName As String, Optional strSheetName As String, Optional strFileName As String)

    Dim rst As DAO.Recordset
    Dim ApXL As Object
    Dim xlWBk As Object
    Dim xlWSh As Object
    Dim intCount As Integer
    Const xlToRight As Long = -4161
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
    Const xlContinuous As Long = 1

    On Error GoTo ExportToExcel_Err
    DoCmd.Hourglass True

    Select Case strObjectType

    Case "Table", "Query"
        Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
    Case "Form"
        Set rst = Forms(strObjectName).RecordsetClone
    Case "Report"
        Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
    End Select

    If rst.RecordCount = 0 Then
        MsgBox "No records to be exported.", vbInformation, GetDBTitle
        DoCmd.Hourglass False
    Else
        On Error Resume Next
        Set ApXL = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Set ApXL = CreateObject("Excel.Application")
        End If
        Err.Clear
        On Error GoTo ExportToExcel_Err

        Set xlWBk = ApXL.Workbooks.Add
        ApXL.Visible = False

        Set xlWSh = xlWBk.Worksheets("Sheet1")
        If Len(strSheetName) > 0 Then
            xlWSh.Name = Left(strSheetName, 31)
        End If

        xlWSh.Range("A1").Select
        Do Until intCount = rst.fields.Count
            ApXL.ActiveCell = rst.fields(intCount).Name
            ApXL.ActiveCell.Offset(0, 1).Select
            intCount = intCount + 1
        Loop

        rst.MoveFirst
        
        xlWSh.Range("A2").CopyFromRecordset rst

        With ApXL
            .Range("A1").Select
            .Range(.Selection, .Selection.End(xlToRight)).Select
            .Selection.Interior.Pattern = xlSolid
            .Selection.Interior.PatternColorIndex = xlAutomatic
            .Selection.Interior.TintAndShade = -0.25
            .Selection.Interior.PatternTintAndShade = 0
            .Selection.Borders.LineStyle = xlNone
            .Selection.AutoFilter
            .Cells.EntireColumn.AutoFit
            .Cells.EntireRow.AutoFit
            .Range("B2").Select
            .ActiveWindow.FreezePanes = True
            .ActiveSheet.Cells.Select
            .ActiveSheet.Cells.WrapText = False
            .ActiveSheet.Cells.EntireColumn.AutoFit
            xlWSh.Range("A1").Select
            .Visible = True
        End With

retry:
        If FileExists(strFileName) Then
            Kill strFileName
        End If
        If strFileName <> "" Then
            xlWBk.SaveAs strFileName, FileFormat:=56
        End If
        
        rst.Close
        Set rst = Nothing
        DoCmd.Hourglass False
    End If

ExportToExcel_Exit:
    DoCmd.Hourglass False
    Exit Function

ExportToExcel_Err:
    DoCmd.SetWarnings True
    MsgBox Err.Description, vbExclamation, Err.Number
    DoCmd.Hourglass False
    Resume ExportToExcel_Exit

End Function

The function can be called like this:

Private Sub ExportToExcel_Example()
 Call VBA_Access_ImportExport.ExportToExcel("Table", "Table1", "VBASheet")
End Sub

“High aims form high characters, and great objects bring out great minds” – Tryon Edwards

A Quick Guide to VBA Objects

Task Examples
Declare and Create Dim coll As New Collection
Dim o As New Class1
Declare Only Dim coll As Collection
Dim o As Class1
Create at run time Set coll = New Collection
Set o = New Class1
Assign to Excel Object Dim wk As Workbook
Set wk = Workbooks(«book1.xlsx»)
Assign using CreateObject Dim dict As Object
Set dict = CreateObject(«Scripting.Dictionary»)
Assign to existing object Dim coll1 As New Collection
Dim coll2 As Collection
Set coll2 = coll1
Return from Function Function GetCollection() As Collection

    Dim coll As New Collection
    Set GetCollection = coll

End Function

Receive from Function Dim coll As Collection
Set coll = GetCollection

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba objects video

Introduction

If you are serious about learning VBA then it is important to understand VBA Objects. Using objects is not that difficult. In fact, they make your life much easier.

In this post, you will see how VBA makes brilliant use of objects. How objects such as Collections, Workbooks and Worksheets save you much complexity, time and effort.

In my next post, I will cover creating objects using Class Modules. However, before you create your own it is vital that you understand exactly what they are and why you need them.

So grab your favourite beverage and take a journey into the fascinating world of VBA objects.

What is a VBA Object?

To understand what an object is, we must first look at simple variables. In VBA we have basic data types such as string, integers, double and date.

 
We use these data types when we are creating a variable e.g.

Dim Score As Long, Price As Double
Dim Firstname As String, Startdate As Date

Score = 45
Price = 24.55
Firstname = "John"
Startdate = #12/12/2016#

 
Basic VBA variables have only one purpose. To store a value while our application is running. We either put a value in the variable or read a value from the variable.

Dim Marks As Long

' Store value in Marks
Marks = 90
Marks = 34 + 44
Marks = Range("A1")

' Read value from Marks
Range("B2") = Marks
Debug.Print Marks

 
In VBA we have a Collection which we use to store groups of items. The following code shows an example of using a Collection in VBA

' https://excelmacromastery.com/
Sub UseCollection()
    
    Dim collFruit As New Collection
    
    ' Add item to the collection
    collFruit.Add "Apple"
    collFruit.Add "Pear"
    
    ' Get the number of items in the collection
    Dim lTotal As Long
    lTotal = collFruit.Count    
   
End Sub

 
The Collection is an example of an object. It is more than a variable. That is, it does more than storing a piece of data. We can add items, remove items and get the number of items.

Definition of a VBA Object: An object is a grouping of data and procedures(i.e. Functions and Subs). The procedures are used to perform some task related to the data.

In the Collection the data is the group of the items it stores. The procedures such as Add, Remove, Count then act on this data.

In the Worksheet object, the main data item is the worksheet and all the procedures perform actions related to the worksheet.

 
VBA Objects

Why VBA Uses Objects

An object is used to represent real world or computer based items.

The major benefit of an object is that it hides the implementation details. Take the VBA Collection we looked at above. It is doing some complicated stuff. When an item is added it must allocate memory, add the item, update the item count and so on.

We don’t know how it is doing this and we don’t need to know. All that we need to know is when we use Add it will add the item, Remove will remove the item and Count will give the number of items.

Using objects allows us to build our applications as blocks. Building it this way means you can work on one part without affecting other parts of your application. It also makes it easier to add items to an application. For example, a Collection can be added to any VBA application. It is not affected in any way by the existing code and in turn it will not affect the existing code.

A Real World Analogy

Looking at a real-world example can often be a good way to understand concepts.

Take a car with a combustion engine. When you are driving your car, a lot of complex stuff is happening. For example, fuel gets injected, compressed and ignited leading to combustion. This then causes the wheels of your car to turn.

VBA Object Car

A nice looking combustion engine | © BigStockPhoto.com

 
The details of how this happens are hidden from you. All you expect is that turning the key will start the car, pressing the accelerator will speed it up and pressing the brake will slow it down and so on.

Think of how great your code would be if it was full of these type of objects. Self-contained and dedicated to performing one set of tasks really well. It would make building your applications so much easier.

Object Components

There are three main items that an object can have. These are

  1. Properties – These are used to set or retrieve a value.
  2. Methods – These are function or subs that perform some task on the objects data.
  3. Events – These are function or subs that are triggered when a given event occurs

 
If you look in the Object Browser(F2) or use Intellisense you will notice different icons beside the members of an object. For example, the screenshot below shows the first three members of the Worksheet object

VBA Objects

 
What these icons mean is as follows

VBA Object Icons

 
 
Let’s take a look at the first three members of the worksheet.

It has an Activate method which we can use to make worksheet active.
It has an Activate event which is triggered when the worksheet is activated.
The Application property allows us to reference the application(i.e. Excel).

' Prints "Microsoft Excel"
Debug.Print Sheet1.Application.Name

' Prints the worksheet name
Debug.Print Sheet1.Name

 
In the next sections we will look at each of these components in more detail.
 

Object Properties

An object property allows us to read a value from the object or write a value to the object. We read and write to a property the same way we read and write to a variable.

' Set the name 
sheet1.Name = "Accounts"

' Get the name
sName = sheet1.Name

 
A property can be read-only which means we can read the value but we cannot update the value.

In the VBA Range, Address is a read-only property

' The address property of range
Debug.Print Sheet1.Range("A1").Address

 
The workbook property Fullname is also a read-only property

' The Fullname property of the Workbook object
sFile = ThisWorkbook.Fullname

 
Properties can also Set and Get objects. For example, the Worksheet has a UsedRange property that return a Range object

Set rg = Sheet1.UsedRange

 
You will notice we used the Set keyword here. We will be looking at this in detail later in the post.

Object Methods

A method is a Sub or a Function. For example, Add is a method of the Collection

' Collection Add method
Coll.Add "Apple"

 
Methods are used to perform some action to do with the object data. With a Collection, the main data is the group of items we are storing. You can see that the Add, Remove and Count methods all perform some action relating to this data.

Another example of a method is the Workbook SaveAs method

Dim wk As Workbook
Set wk = Workbooks.Open "C:DocsAccounts.xlsx"
wk.SaveAs "C:DocsAccounts_Archived.xlsx"

 
and the Worksheets Protect and Copy methods

sheet1.Protect "MyPassword"
Sheet1.Copy Before:=Sheet2

Object Events

Visual Basic is an event-driven language. What this means is that the code runs when an event occurs. Common events are button clicks, workbook Open, worksheet Activate etc.

In the code below we display a message each time Sheet1 is activated by the user. This code must be placed in the worksheet module of Sheet1.
 

Private Sub Worksheet_Activate()
    MsgBox "Sheet1 has been activated."
End Sub

 
Now that we know the parts of the VBA object let’s look at how we use an object in our code.

Creating a VBA Object

In VBA, our code must “Create” an object before we can use it. We create an object using the New keyword.

If we try to use an object before it is created we will get an error. For example, take a look at the code below

Dim coll As Collection

coll.Add "Apple"

 
When we reach the Add line no Collection has been created.

VBA Object nothing

 
If we try to run this line we get the following error

VBA Object Variable

 
There are three steps to creating a VBA object

  1. Declare the variable.
  2. Create a new object.
  3. Assign the variable to the object.

 
We can perform these steps in one line using Dim and New together. Alternatively, we can declare the variable in one line and then create and assign the object in another line using Set.

Let’s take a look at both of these techniques.

Using Dim with New

When we use Dim and New together they declare, create and assign all in one line.

' Declare, Create and Assign
Dim coll As New Collection

 
Using code like does not provide much flexibility. It will always create exactly one Collection when we run our code.

In the next section we will look at Set. This allows us to create objects based on conditions and without having to declare a variable for each new object.

Using Set with New

We can declare an object variable in one line and then we can use Set to create and assign the object on another line. This provides us with a lot of flexibility.

In the code below we declare the object variable using Dim. We then create and assign it using the Set keyword.

' Declare
Dim coll As Collection
' Create and Assign
Set coll = New Collection

 
We use Set in this way when the number of objects can vary. Using Set allows us to create multiple objects. In other words, we can create objects as we need them. We can’t do this using Dim and New.

We can also use conditions to determine if we need to create an object e.g.

Dim coll As Collection

' Only create collection if cell has data
If Range("A1") <> "" Then
    Set coll = New Collection
End If

 
Later in this post we will see some examples of using Set to create objects.

Subtle Differences of Dim Versus Set

There are some subtle differences between using New with Set and using New with Dim.
When we use New with Dim, VBA does not create the object until the first time we use it.

In the following code, the collection will not be created until we reach the line that adds “Pear”.

Dim coll As New Collection

' Collection is created on this line
coll.Add "Pear"

 
If you put a breakpoint on the Add line and check the variable value you will see the following message

Object variable or With block variable not set

When the Add line runs, the Collection will be created and the variable will now show a Collection with one item.

The reason for this is as follows. A Dim statement is different to other VBA lines of code. When VBA reaches a Sub/Function it looks at the Dim statements first. It allocates memory based on the items in the Dim statements. It is not in a position to run any code at this point.

Creating an object requires more than just allocating memory. It can involve code being executed. So VBA must wait until the code in the Sub is running before it can create the object.

Using Set with New is different in this regard to using Dim with New. The Set line is used by VBA when the code is running so VBA creates the object as soon as we use Set and New e.g.

Dim coll As Collection

' Collection is created on this line
Set coll = New Collection

coll.Add "Pear"

 
There is another subtlety to keep in mind using New. If we set the object variable to Nothing and then use it again, VBA will automatically create a new object e.g.

' https://excelmacromastery.com/
Sub EmptyColl2()
 
    ' Create collection and add items
    Dim coll As New Collection
 
    ' add items here
    coll.Add "Apple"
 
    ' Empty collection
    Set coll = Nothing
 
    ' VBA automatically creates a new object
    coll.Add "Pear"
 
End Sub

 
If we used Set in the above code to create the new Collection then the “Add Pear” line would cause an error.

When New Is Not Required

You may have noticed some objects don’t use the New keyword.

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Sheet1")
Dim wk As Workbook
Set wk = Workbooks.Open("C:DocsAccounts.xlsx")

When a workbook, is opened or created, VBA automatically creates the VBA object for it. It also creates the worksheet object for each worksheet in that workbook.

Conversely, when we close the workbook VBA will automatically delete the VBA objects associated with it.

This is great news. VBA is doing all the work for us. So when we use Workbooks.Open, VBA opens the file and creates the workbook object for the workbook.

An important point to remember is that there is only one object for each workbook. If you use different variables to reference the workbook they are all referring to the same object e.g.

Dim wk1 As Workbook
Set wk1 = Workbooks.Open("C:DocsAccounts.xlsx")

Dim wk2 As Workbook
Set wk2 = Workbooks("Accounts.xlsx")

Dim wk3 As Workbook
Set wk3 = wk2

We will look at this in more detail in the VBA Objects in Memory section below.

Using CreateObject

There are some very useful libaries that are not part of Excel VBA. These include the Dictionary, Database objects, Outlook VBA objects, Word VBA objects and so on.

These are written using COM interfaces. The beauty of COM is that we can easily use these libraries in our projects.

If we add a reference to the library we create the object in the normal way.

' Select Tools->References and place a check 
' beside "Microsoft Scripting Runtime"
Dim dict As New Scripting.Dictionary

 
If we don’t use a reference we can create the object at run time using CreateObject.

Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")

 
The first method is referred to as Early Binding and the second is referred to as Late Binding(see Early versus Late Binding) for more details.

Assigning VBA Objects

We can assign basic variables using the Let keyword.

Dim sText As String, lValue As Long

Let sText = "Hello World"
Let lValue = 7

 
The Let keyword is optional so nobody actually uses it. However, it is important to understand what it is used for.

sText = "Hello World"
lValue = 7

 
When we assign a value to a property we are using the Let Property

' Both lines do the same thing
sheet1.Name = "Data"
Let sheet1.Name = "Data"

 
When we assign an object variable we use the Set keyword instead of the Let keyword. When I use “object variable” I mean any variable that isn’t a basic variable such as a string, long or double etc..

' wk is the object variable
Dim wk As Worksheet
Set wk = ThisWorkbook.Worksheets(1)

' coll1 is the object variable
Dim coll1 As New Collection
coll1.Add "Apple"

' coll2 is the object variable
Dim coll2 As Collection
Set coll2 = coll1

 
Using the Set keyword is mandatory. If we forget to use Set we will get the error below

coll2 = coll1

 
VBA Set

 
It may look like Let and Set are doing the same thing. But they are actually doing different things:

  • Let stores a value
  • Set stores an address

 
To understand more about this we need to take a peek(pun intended:-)) into memory.

VBA Objects in Memory

“Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it” – Alan Perlis

 
To understand what New and Set are doing we need to understand how variables are represented in memory.

When we declare variables, VBA creates a slot for them in memory. You can think of the slot as an Excel cell in memory.

Dim X As long, Y As Long

 
VBA Set Memory

 
When we assign values to these variables, VBA places the new values in the appropriate slots.

X = 25
Y = 12

 
VBA Basic Memory

 
We saw the following line of code earlier in this post

Dim coll As New Collection
 

 
This line creates the object in memory. However, it doesn’t store this object in the variable. It

stores the address of the object

in the variable. In programming, this is known as a Pointer.

VBA Objects in Memory

Because VBA handles this seamlessly it can seem as if the object variable and the object are the same thing. Once we understand they are different it is much easier to understand what Set is actually doing.

How Set Works

Take a look at the following code

Dim coll1 As New Collection
Dim coll2 As Collection

Set coll2 = coll1

Only one Collection has been created here. So coll1 and coll2 refer to the same Collection.

In this code, coll1 contains the address of the newly created Collection.

When we use Set we are copying the address from coll1 to coll2. So now they are both “pointing” to the same Collection in memory.

 
VBA Objects in Memory

 
Earlier in the post we looked at Workbook variables. Let’s have a look at this code again

Dim wk1 As Workbook
Set wk1 = Workbooks.Open("C:DocsAccounts.xlsx")

Dim wk2 As Workbook
Set wk2 = Workbooks("Accounts.xlsx")

Dim wk3 As Workbook
Set wk3 = Workbooks(2)

When we open the workbook Accounts.xlsx, VBA creates an object for this workbook. When we assign the workbook variables in the code above, VBA places the address of the workbook object in the variable.

In this code example, the three variables are all referring to the same workbook object.

VBA Workbook Object

If we use code like the following

wk1.SaveAs "C:TempNewName.xlsx"

VBA uses the address in wk1 to determine the workbook object to use. It does this seamlessly so when we use a workbook variable it looks like we are referring directly to the object.

To sum up what we have learned in this section:

  • Let writes a value to a basic variable
  • Set writes an address to an object variable

Objects and Procedures

In VBA we can refer to Functions and Subs as procedures. When we pass an object to a procedure only the address passed.

When we pass an object from a Function(Subs cannot return anything) only the address of the object is passed back.

In the code below we have one collection. It is the address that gets passed to and from the function.

' https://excelmacromastery.com/
Sub TestProc()
    
    ' Create collection
    Dim coll1 As New Collection
    coll1.Add "Apple"
    coll1.Add "Orange"

    Dim coll2 As Collection
    ' UseCollection passes address back to coll2
    Set coll2 = UseCollection(coll1)

End Sub

' Address of collection passed to function
Function UseCollection(coll As Collection) _
                        As Collection
    Set UseCollection = coll
End Function

Using ByRef and ByVal

When we pass a simple variable to a procedure we can pass using ByRef or ByVal.

ByRef means we are passing the address of the variable. If the variable changes in the procedure the original will also be changed.
ByVal means we are creating a copy of the variable. If the variable changes in the procedure the original will not be changed.

' Pass by value
Sub PassByVal(ByVal val As Long)

' Pass by reference
Sub PassByRef(ByRef val As Long)
Sub PassByRef(val As Long)

 
Most of the time it is a good idea to use ByVal because it prevents the variable being accidentally changed in a procedure.

When we pass a Collection to a procedure, we are always passing the address of the Collection.

ByRef and ByVal only affect the object variable. They do not affect the object!

What this means is that if we change the object in the procedure it will be changed outside it – this is regardless of whether you use ByVal or ByRef.

For example, in the code below we have two procedures that change the Collection. One uses ByRef and one uses ByVal. In both cases the Collection has changed when we return to the TestProcs Sub

' https://excelmacromastery.com/
Sub TestProcs()
    Dim c As New Collection
    c.Add "Apple"
    
    PassByVal c
    ' Prints Pear
    Debug.Print c(1)
    
    PassByRef c
    ' Prints Plum
    Debug.Print c(1)
   
End Sub

' Pass by value
Sub PassByVal(ByVal coll As Collection)
    ' Remove current fruit and add Pear
    coll.Remove (1)
    coll.Add "Pear"
End Sub

' Pass by reference
Sub PassByRef(ByRef coll As Collection)
    ' Remove current fruit and add Plum
    coll.Remove (1)
    coll.Add "Plum"
End Sub

Let’s look at a second example. Here we are setting the object variable to “point” to a new Collection. In this example, we get different results from ByVal and ByRef.

In the PassByVal Sub, a copy of the original object variable is created. So it is this copy that points to the new Collection. So our original object variable is not affected.

In the PassByRef Sub we are using the same object variable so when we point to the New Collection, our original object variable is now pointing to the new collection.

' https://excelmacromastery.com/
Sub TestProcs()

    Dim c As New Collection
    c.Add "Apple"
    
    PassByVal c
    ' Prints Apple as c pointing to same collection
    Debug.Print c(1)
    
    PassByRef c
    ' Prints Plum as c pointing to new Collecton
    Debug.Print c(1)

End Sub

' Pass by value
Sub PassByVal(ByVal coll As Collection)
    Set coll = New Collection
    coll.Add "Orange"
End Sub

' Pass by reference
Sub PassByRef(ByRef coll As Collection)
    Set coll = New Collection
    coll.Add "Plum"
End Sub

Why VBA Uses Pointers

You may be wondering why VBA uses pointers. The reason is that it is much more efficient.

Imagine you had a Collection with 50000 entries. Think how inefficient it would be to create multiple copies of this Collection when your application was running.

Think of it like a library which is a real world collection of books. We can put the Library address in directories, newspapers etc. A person simply uses the address to go to the Library and add and remove books.

There is one Libary and the address is passed around to anyone who needs to use it.If we wanted a second library we would create a new library. It would have a different address which we could also pass around.

VBA Object - Library

© BigStockPhoto.com

Running a Simple Memory Experiment

To demonstrate what we have been discussing, let’s look at a code example. The code below uses

  • VarPtr to give the memory address of the variable
  • ObjPtr to give the memory address of the object

 
The memory address is simply a long integer and it’s value is not important. But what is interesting is when we compare the addresses.

' https://excelmacromastery.com/
Sub Memory()

    Dim coll1 As New Collection
    Dim coll2 As Collection
    
    Set coll2 = coll1
    
    ' Get address of the variables Coll1 and Coll2
    Dim addrColl1 As Long, addrColl2 As Long
    addrColl1 = VarPtr(coll1)
    addrColl2 = VarPtr(coll2)
    
    Debug.Print "Address of the variable coll1 is " & addrColl1
    Debug.Print "Address of the variable coll2 is " & addrColl2
    
    ' Get address of the Collection they point to
    Dim addrCollection1 As Long, addrCollection2 As Long
    addrCollection1 = ObjPtr(coll1)
    addrCollection2 = ObjPtr(coll2)
    
    Debug.Print "Address coll1 collection is " & addrCollection1
    Debug.Print "Address coll2 collection is " & addrCollection2

End Sub

 
Note: Use LongPtr instead of Long if you are using a 64 bit version of Excel.

When you run the code you will get a result like this:

Address of the variable coll1 is 29356848
Address of the variable coll2 is 29356844
Address coll1 collection is 663634280
Address coll2 collection is 663634280

 
you will notice

  • The memory addresses will be different each time you run.
  • The address of the coll1 Collection and the coll2 Collection will always be the same.
  • The address of the coll1 variable and the coll2 variable will always be different.

 
This shows that we have two different variables which contain the address of the same Collection.

Cleaning Up Memory

So what happens if we set a variable to a New object multiple times? In the code below we use Set and New twice for the variable coll

Dim coll As Collection

Set coll = New Collection
coll.Add "Apple"

' Create a new collection and point coll to it
Set coll = New Collection

 
In this example, we created two new Collections in memory. When we created the second collection we set coll to refer to it. This means it no longer refers to the first collection. In fact, nothing is referring to the first Collection and we have no way of accessing it.

In some languages(looking at you C++) this would be a memory leak. In VBA however, this memory will be cleaned up automatically. This is known as Garbage Collection.

Let me clarify this point. If an object has no variable referring to it, VBA will automatically delete the object in memory. In the above code, our Collection with “Apple” will be deleted when coll “points” to a new Collection.

Clean Up Example

If you want to see this for yourself then try the following.

Create a class module, call it clsCustomer and add the following code.

Public Firstname As String

Private Sub Class_Terminate()
    MsgBox "Customer " & Firstname & " is being deleted."
End Sub

 
Class_Terminate is called when an object is being deleted. By placing a message box in this event we can see exactly when it occurs.

Step through the following code using F8. When you pass the Set oCust = New clsCustomer line you will get a message saying the Jack was deleted.When you exit the function you will get the message saying Jill was deleted.

' https://excelmacromastery.com/
Sub TestCleanUp()
    
    Dim oCust As New clsCustomer
    oCust.Firstname = "Jack"
    
    ' Jack will be deleted after this line
    Set oCust = New clsCustomer
    oCust.Firstname = "Jill"
    
End Sub

 
VBA automatically deletes objects when they go out of scope. This means if you declare them in a Sub/Function they will go out of scope when the Function ends.

Setting Objects to Nothing

In code examples you may see code like

Set coll = Nothing

 
A question that is often asked is “Do we need to Set variables to Nothing when we are finished with them?”. The answer is most of the time you don’t need to.

As we have seen VBA will automatically delete the object as soon as we go out of scope. So in most cases setting the object to Nothing is not doing anything.

The only time you would set a variable to Nothing is if you needed to empty memory straight away and couldn’t wait for the variable to go out of scope. An example would be emptying a Collection.

Imagine the following project. You open a workbook and for each worksheet you read all the customer data to a collection and process it in some way. In this scenario, you would set the Collection to Nothing every time you finish with a worksheet’s data.

' https://excelmacromastery.com/
Sub SetToNothing()
 
    ' Create collection
    Dim coll As New Collection
 
    Dim sh As Worksheet
    ' Go through all the worksheets
    For Each sh In ThisWorkbook.Worksheets
   
        ' Add items to collection
        
        ' Do something with the collection data
        
        ' Empty collection
        Set coll = Nothing
 
    Next sh
 
End Sub

Memory Summary

To sum up what we have learned in this section:

  1. A new object is created in memory when we use the New keyword.
  2. The object variable contains only the memory address of the object.
  3. Using Set changes the address in the object variable.
  4. If an object is no longer referenced then VBA will automatically delete it.
  5. Setting an object to Nothing is not necessary in most cases.

Why Set Is Useful

Let’s look at two examples that show how useful Set can be.

First, we create a very simple class module called clsCustomer and add the following code

Public Firstname As String
Public Surname As String

Set Example 1

In our first scenario, we are reading from a list of customers from a worksheet. The number of customers can vary between 10 and 1000.

Obviously, declaring 1000 objects isn’t an option. Not only is it a lot of wasteful code, it also means we can only deal with maximum 1000 customers.

' Don't do this!!!
Dim oCustomer1 As New clsCustomer
Dim oCustomer2 As New clsCustomer
' .
' .
' .
Dim oCustomer1000 As New clsCustomer

 
What we do first is to get the count of rows with data. Then we create a customer object for each row and fill it with data. We then add this customer object to the collection.

' https://excelmacromastery.com/
Sub ReadCustomerData()

    ' We will always have one collection
    Dim coll As New Collection
    
    ' The number of customers can vary each time we read a sheet
    Dim lLastRow As Long
    lLastRow = Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp).Row
    
    Dim oCustomer As clsCustomer
    Dim i As Long
    ' Read through the list of customers
    For i = 1 To lLastRow
    
        ' Create a new clsCustomer for each row
        Set oCustomer = New clsCustomer
        
        ' Add data
        oCustomer.Firstname = Sheet1.Range("A" & i)
        oCustomer.Surname = Sheet1.Range("B" & i)
        
        ' Add the clsCustomer object to the collection
        coll.Add oCustomer
        
    Next i

End Sub

 
Each time we use Set we are assigning oCustomer to “point” to the newest object. We then add the customer to the Collection. What happens here is that VBA creates a copy of the object variable and places it in the collection.

Set Example 2

Let’s look at a second example where using Set is useful. Imagine we have a fixed number of customers but only want to read the ones whose name starts with the letter B. We only create a customer object when we find a valid one.

' https://excelmacromastery.com/
Sub ReadCustomerB()

    ' We will always have one collection
    Dim coll As New Collection
   
    Dim oCustomer As clsCustomer, sFirstname As String
    Dim i As Long
    ' Read through the list of customers
    For i = 1 To 100
    
        sFirstname = Sheet1.Range("A" & i)
        
        ' Only create customer if name begins with B
        If Left(sFirstname, 1) = "B" Then
            ' Create a new clsCustomer
            Set oCustomer = New clsCustomer
            
            ' Add data
            oCustomer.Firstname = sFirstname
            oCustomer.Surname = Sheet1.Range("B" & i)
            
            ' Add to collection
            coll.Add oCustomer
        End If
        
    Next i

End Sub

 
It doesn’t matter how many customer names start with B this code will create exactly one object for each one.

 
This concludes my post on VBA Objects. I hope you found it beneficial.In my next post I’ll be looking at how you can create your own objects in VBA using the Class Module.

If you have any questions or queries please feel free to add a comment or email me at Paul@ExcelMacroMastery.com.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Like this post? Please share to your friends:
  • Vba excel 2007 массив
  • Vba access excel cells
  • Vba excel 2007 для начинающих
  • Vb net сохранить файл excel
  • Vba enter в ячейке excel