Creating objects in excel vba

“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.)

VBA Create Object

Create Object in VBA

Create object is a function that is used to create and reference the ActiveX objects. An ActiveX object is an object which is used for automation interfaces. Objects are entities in VBA which comprises of code, Excel VBA Create Object allows us to create objects in VBA. To reference objects in there are two types of bindings that are invoked in VBA one is early binding which uses the library or VBA and another is late binding which is used to reference by set statement.

Create Object can be classified into two parts, one is mandatory while another is optional. The Mandatory part is known as the class which is the application name or the interface name which we are trying to create and another optional part is known as server name means the location of the server where the object will be created.

How to Use Create Object Function in VBA Excel?

To create an object we need to declare any variable with an object data type and then we use the set statement to reference it. After that, we use to create object to create an object with reference to the application we are referring to.

You can download this VBA Create Object Excel Template here – VBA Create Object Excel Template

Example #1

In this first example, we will try to use Create Object and open word file application. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Once we have a module in our project explorer we can begin with our example, write the subprocedure of VBA Create Object Function.

Code:

Sub Example1()

End Sub

VBA Create Object Example 1-2

Step 3: Now we declare word and doc as an object.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object

End Sub

VBA Create Object Example 1-3

Step 4: Now let us assume that we may encounter an error so we will use error handling from the first hand.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object
On Error Resume Next

End Sub

VBA Create Object Example 1-4

Step 5: As soon as we declare an object in VBA it invokes late binding which means it overrides the virtual method so we need to use the Set keyword.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application")

End Sub

VBA Create Object Example 1-5

Step 6: The above statement will generate an error if the word is not open and the error will be “429” which means we have given too many requests for VBA in a little amount of time so, we take note that to avoid this error we need to keep word open for best circumstances, but if we do encounter an error we can clear it by the following code as shown below.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application")
If Err.Number = 429 Then
Err.Clear

End Sub

VBA Create Object Example 1-6

Step 7: Now we will create the object for word application using the create object method.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application")
If Err.Number = 429 Then
Err.Clear
Set word = CreateObject("Word.Application")
End If

End Sub

VBA Create Object Example 1-7

Step 8: Now we can check if Word is open or not and if it is not open we can open it by the following code.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application")
If Err.Number = 429 Then
Err.Clear
Set word = CreateObject("Word.Application")
End If
If Not word Is Nothing Then
word.Visible = True

End Sub

Word File Example 1-8

Step 9: Also if word is not open we can show an error message.

Code:

Sub Example1()

Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application")
If Err.Number = 429 Then
Err.Clear
Set word = CreateObject("Word.Application")
End If
If Not word Is Nothing Then
word.Visible = True
Else
MsgBox "Cannot open Word."
End If

End Sub

VBA Create Object Example 1-9

Step 10: When we run the above code by pressing function key F5 and to run the code, click on the Play button. we can see that word is open.

Word File Example 1-10

Example #2

In this example, we will use the excel application to open excel and write a value in any row. For this, follow the below steps:

Step 1: In the same module we can begin declaring another subprocedure as shown below,

Code:

Sub Example2()

End Sub

VBA Create Object Example 2-1

Step 2: We will Create an excel object in the code as shown below,

Code:

Sub Example2()

Dim ExcelSheet As Object

End Sub

VBA Create Object Example 2-2

Step 3: Now we know that as soon as we declare an object and it invokes late binding so we need to set the object as shown below,

Code:

Sub Example2()

Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")

End Sub

VBA Create Object Example 2-3

Step 4: So now we need to open excel means we have to make it visible and only by that way we will be able to use it as shown below,

Code:

Sub Example2()

Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")
ExcelSheet.Application.Visible = True

End Sub

VBA Create Object Example 2-4

Step 5: Now we can write anything in excel so for this example let us try it in the first row as shown below,

Code:

Sub Example2()

Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")
ExcelSheet.Application.Visible = True
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"

End Sub

Excel Sheet Example 2-5

Step 6: We can also save the excel file for future references.

Code:

Sub Example2()

Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")
ExcelSheet.Application.Visible = True
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
ExcelSheet.SaveAs "D:TEST.XLS"
ExcelSheet.Application.Quit
Set ExcelSheet = Nothing

End Sub

Excel Sheet Example 2-6

Step 7: Now we can free the excel object from the following codes.

Code:

Sub Example2()

Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")
ExcelSheet.Application.Visible = True
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
ExcelSheet.SaveAs "D:TEST.XLS"

End Sub

Excel Sheet Example 2-7

Step 8: When we run the above code by pressing function key F5 and to run the code, click on the Play button. we can see that an excel sheet is created in the path provided in the above line of code also we can see from the result of the code in the file created as follows.

VBA Create Object Example 2-8

Things to Remember

There are some key points which we need to remember about VBA Create Object and they can be classified as follows:

  • When we reference an object it invokes two types of Binding Late Binding and Early Binding.
  • Set statement is used to reference the object when late binding is invoked.
  • Late Binding is also known as dynamic binding.
  • Intellisense is not accessible in create object method.

Recommended Articles

This is a guide to the VBA Create Object. Here we discuss how to use create object function in excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA LBound
  2. VBA Solver
  3. VBA Login
  4. VBA Month

CreateObject Function in VBA

Objects are very important concepts in VBA coding, and understanding an object’s work model is quite complex. When we reference the objects in VBA coding, we do it in two ways: “Early Binding” and “Late Binding.” “Early Binding” is the process of setting the object reference from the references library of the VBA. When we send the file to someone else, they must also set the reference to those respective objects. However, “Late Binding” does not require the user to set any object references because, in late binding coding, we set the reference to the respective object using the VBA “CreateObject” function.

Table of contents
  • CreateObject Function in VBA
    • What is the CreateObject in Excel VBA?
    • Example of Create Object Function in Excel VBA
      • Example #1
      • Example #2
    • Things to Remember About CreateObject in VBA
    • Recommended Articles

VBA CreateObject-updated

What is the CreateObject in Excel VBA?

“Create Object,” as the name says, will create the mentioned object from the Excel VBA. So, the Create Object function returns the reference to an object initiated by an Active X component.

Below is the syntax of the CreateObject function in VBA: –

VBA CreateObject Syntax

  • Class: The name of the object that we are trying to initiate and set the reference to the variable.
  • [Server Name]: This is an optional parameter; if ignored, it will use the local machine only.

Example of Create Object Function in Excel VBA

Below are the examples of VBA CreateObject.

You can download this VBA CreateObject Excel Template here – VBA CreateObject Excel Template

Example #1

Now, we will see how to initiate a PowerPoint application from Excel using the CreateObject function in VBA. But, first, open the Excel file and go to the Visual Basic Editor window by pressing the ALT + F11 key.

Code:

Sub CreateObject_Example1()

End Sub

VBA CreateObject Example 1

Declare the variable as PowerPoint.Application.

VBA CreateObject Example 1-1

As you can see above, when we start typing the word “PowerPoint,” we don’t see any IntelliSense list showing the related searches because “PowerPoint” is an external object. But nothing to worry declare the variable as “Object.”

Code:

Sub CreateObject_Example1()

Dim PPT As Object

End Sub

VBA CreateObject Example 1-2

Since we have declared the variable as “Object,” we need to set the reference to the object by using the “Set” keyword. Enter the “Set” keyword, mention the variable, and put an equal sign.

Code:

Sub CreateObject_Example1()

Dim PPT As Object

Set PPT =

End Sub

VBA CreateObject Example 1-3

Now, open the CreateObject function.

VBA CreateObject Example 1-4

Since we are referencing the external object of “PowerPoint” for the “Class” parameter of the Create Object function, mention the external object name in doubles quotes as “PowerPoint.Application.”

Code:

Sub CreateObject_Example1()

Dim PPT As Object

Set PPT = CreateObject("PowerPoint.Application")

End Sub

Powerpoint.applictaion Example 1-5

Now, the CreateObject function will initiate the PowerPoint application. Once we initiate the object, we need to make it visible using the variable name.

Example 1-6

One of the problems with the CreateObject method or late binding method is we don’t get to see the IntelliSense list now. So it would be best if you were sure about the code you are writing.

For the variable “PPT,” use the “Visible” property and set the status as “True.”

Code:

Sub CreateObject_Example1()

Dim PPT As Object

Set PPT = CreateObject("PowerPoint.Application")

PPT.Visible = True

End Sub

excel VBA Create Object Example 1-7

To add a slide to PPT, define the below-line VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Code:

Sub CreateObject_Example1()

Dim PPT As Object

Set PPT = CreateObject("PowerPoint.Application")

PPT.Visible = True
PPT.Presentations.Add

End Sub

Now, execute the code manually or through the F5 key and see the “PowerPoint” application opens up.

VBA CreateObject Example 1-9

Once the PowerPoint application is enabled using the variable “PPT,” we can start accessing the PowerPoint application.

Example #2

Now, we will see how to initiate an Excel application using the CreateObject function in VBA. Once again, declare the variable as “Object.”

Code:

Sub CreateObject_Example2()

Dim ExcelSheet As Object

End Sub

Example 2

The moment we declare the variable as an object, it causes late binding, and we need to use the “Set” keyword to set the reference for the required object.

Example 1-8

Since we are referencing an Excel worksheet from the application Excel, enter “Excel. Sheet” in double quotes.

Code:

Sub CreateObject_Example2()

Dim ExcelSheet As Object

Set ExcelSheet = CreateObject("Excel.Sheet")

End Sub

Example 2-1

Once we set the reference for the Excel sheet, we need to make it visible to use it. It is similar to how we made the PowerPoint application visible.

Code:

Sub CreateObject_Example2()

Dim ExcelSheet As Object

Set ExcelSheet = CreateObject("Excel.Sheet")

ExcelSheet.Application.Visible = True

End Sub

Example 2-2

Now, it will activate the Excel worksheet.

Similarly, we can use the code to initiate an Excel workbook from other Microsoft products.

Code:

Sub CreateObject_Example3()

Dim ExlWb As Object

Set ExlWb = CreateObject("Excel.Application")

ExlWb.Application.Visible = True

End Sub

VBA CreateObject Example 3

Things to Remember About CreateObject in VBA

  • In VBA, we can use the CreateObject function to reference objects.
  • The Create Object function causes a late-binding process.
  • Using the CreateObject function, we do not get to access the IntelliSense list of VBA.

Recommended Articles

This article has been a guide to CreateObject in VBA. Here, we discuss creating a reference object using the Createobject function in Excel VBA, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA String to Date
  • SendKeys in Excel VBA
  • VBA GetObject
  • VBA FileSystemObject
  • VBA Const

Содержание

  1. Объектные модели Создание объектов в VBA
  2. 4.2 Создание и удаление объектов
  3. Name already in use
  4. VBA-Docs / Language / Reference / User-Interface-Help / createobject-function.md
  5. Функция CreateObject
  6. Пример
  7. CreateObject function
  8. Syntax
  9. Remarks
  10. Example
  11. See also
  12. Support and feedback

Объектные модели Создание объектов в VBA

4.2 Создание и удаление объектов

Создание объектов в VBA, раннее и позднее связывание (early/late binding), конструкция CreateObject и ключевое слово New, удаление объектов, ключевое слово Nothing

Создание объекта в VBA может производиться разными способами. Первый, самый простой способ выглядит так:

Dim oApp As Object

Set oApp = CreateObject («Word.Application»)

Это — так называемое позднее связывание (late binding). Мы вначале объявляем переменную oApp с возможностью ссылаться на любой объект, а затем присваиваем ей ссылку на создаваемый нами объект Word.Application. Такое позднее связывание хуже с точки зрения производительности и расхода оперативной памяти, кроме того, редактор Visual Basic отказывается нам подсказывать, какие свойства и методы есть у этого объекта. Поэтому позднее связывание есть смысл использовать только тогда, когда вы собираетесь хранить в этой переменной, согласно логике вашей программы, объекты разных типов. В остальных ситуациях предпочтительнее использовать раннее связывание (early binding):

Dim oApp As Word.Application

Set oApp = CreateObject(«Word.Application»)

В этом случае мы сразу присваиваем переменной oApp тип Word.Application, а потом присваиваем ей ссылку на создаваемый нами объект. Можно обойтись и без второй строки:

Dim oApp As New Word.Application

Однако ключевое слово New не может использоваться при создании зависимых объектов, с ключевым словом WithEvents и при создании переменных встроенных типов ( String, Int и т.п.), поэтому иногда необходимо будет использовать только объявление с Set. Кроме того, в языке VBScript синтаксической конструкции New нет, поэтому если вы собираетесь использовать оба языка, лучше сразу привыкать к конструкции CreateObject().

Еще одна возможность создания объекта — воспользоваться методом другого объекта, который создаст нужный нам объект и возвратит на него ссылку напрямую или через коллекцию:

Dim oApp As New Word.Application

Dim oDoc As Word.Document

Set oDoc = oApp.Documents(1)

В этом примере мы вначале создаем объект Word.Application, затем при помощи метода Add() коллекции Documents создаем в этой коллекции новый документ, потом получаем на него ссылку для переменной oDoc, а потом вызываем метод SaveAs() созданного нами объекта документа.

Удаление объектов производится очень просто:

Set объектная_переменная = nothing

Set oApp = nothing

В принципе, объект можно и не удалять — он будет удален автоматически после того, как последняя объектная переменная, которая на него ссылается, уйдет за область видимости (обычно это значит, что закончит работу процедура, в которой он используется). Однако явное удаление объектов — это «правило хорошего тона», которое позволит вам при создании серьезных приложений избежать конфликтов имен и перерасхода ресурсов.

Еще один момент, связанный с удалением объектов. Не все объекты можно удалить при помощи синтаксической конструкции Set объектная_переменная = nothing. Некоторые объекты требуют, чтобы их удаляли из памяти специальным способом. Например, объект приложения Word, который мы создавали в нашем примере, хочет, чтобы для его удаления из памяти был обязательно вызван его метод Quit() — иначе он выдаст сообщение об ошибке.

Источник

Name already in use

VBA-Docs / Language / Reference / User-Interface-Help / createobject-function.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Creates and returns a reference to an ActiveX object.

CreateObject(class, [ servername ])

The CreateObject function syntax has these parts:

Part Description
class Required; Variant (String). The application name and class of the object to create.
servername Optional; Variant (String). The name of the network server where the object will be created. If servername is an empty string («»), the local machine is used.

The class argument uses the syntax appname.objecttype and has these parts:

Part Description
appname Required; Variant (String). The name of the application providing the object.
objecttype Required; Variant (String). The type or class of object to create.

Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

To create an ActiveX object, assign the object returned by CreateObject to an object variable.

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. After an object is created, you reference it in code by using the object variable you defined. In the following example, you access properties and methods of the new object by using the object variable, ExcelSheet , and other Microsoft Excel objects, including the Application object and the Cells collection.

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name; for a share named «MyServerPublic,» servername is «MyServer.»

The following code returns the version number of an instance of Excel running on a remote computer named MyServer :

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

[!NOTE] Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

This example uses the CreateObject function to set a reference ( xlApp ) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.

Источник

Функция CreateObject

Примечание: Функция, метод, объект или свойство, описанные в данном разделе, отключаются, если служба обработки выражений Microsoft Jet выполняется в режиме песочницы, который не позволяет рассчитывать потенциально небезопасные выражения. Для получения дополнительных сведений выполните в справке поиск по словам «режим песочницы».

Создает и возвращает ссылку на объект ActiveX.

Функция CreateObject имеет следующие аргументы:

Обязательный аргумент. Variant ( String). Имя приложения и класс создаваемого объекта.

Необязательный аргумент. Variant ( String). Имя сетевого сервера, где будет создан объект. Если имя_сервера является пустой строкой («»), используется локальный компьютер.

Аргумент классаргумент использует синтаксис имя_приложения . тип_объекта и содержит следующие части:

Обязательный аргумент. Variant ( String). Имя приложения, предоставляющего объект.

Обязательный аргумент. Variant ( String). Тип (класс) объекта, который требуется создать.

В каждом приложении, поддерживающем автоматизацию, имеется хотя бы один тип объекта. Например, в приложении для обработки текстов могут быть объекты Application, Document и Toolbar.

Чтобы создать ActiveX, назначьте объекту CreateObject объекту, объектная переменная:

Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.

В этом примере мы автоматиз будем автоматизировать объект электронной таблицы Excel из базы данных Access. Этот код запускает приложение, созда которое создает объект, в данном случае таблицу Microsoft Excel. На созданный объект можно ссылаться в коде с помощью определенной вами объектной переменной. В следующем примере доступ к свойствам и методам нового объекта осуществлялся с помощью объектной переменной, ExcelSheet и других объектов Excel, включая объект Application и коллекцию Cells .

При объявлении объектной переменной с помощью предложения As Object создается переменная, которая может содержать ссылку на любой тип объекта. Однако обращение к объекту через эту переменную выполняется с поздним связыванием, то есть привязка создается при выполнении программы. Чтобы создать объектную переменную с ранним связыванием, то есть со связыванием при компиляции программы, объявите объектную переменную с определенным идентификатором класса. Например, объявите и создайте следующие ссылки Excel:

С помощью ссылки на ранняя переменная можно улучшить производительность, но она может содержать только ссылку на класс, заданную в объявление.

Можно передать объект, возвращаемый функцией CreateObject, функции, которая использует объект в качестве аргумента. Например, в следующем коде создается и передается ссылка на объект Excel.Application:

Call MySub (CreateObject(«Excel.Application»))

Вы можете создать объект на удаленном компьютере, подключенном к сети, указав его имя в аргументе имя_сервера функции CreateObject. Это имя совпадает с именем компьютера в имени общего ресурса: для имени «\MyServerPublic» имя_сервера будет «MyServer».

Примечание: Дополнительные сведения о том, как сделать приложение видимым на удаленном сетевом компьютере, см. в документации COM ( Microsoft Developer Network). Возможно, понадобится добавить раздел реестра для приложения.

Следующий код возвращает номер версии экземпляра приложения Excel, запущенного на удаленном компьютере с именем MyServer :

Если удаленный сервер не существует или недоступен, возникает ошибка во время выполнения.

Примечание: Используйте функцию CreateObject, если текущий экземпляр объекта отсутствует. Если экземпляр объекта уже запущен, запускается новый экземпляр и создается объект указанного типа. Чтобы использовать текущий экземпляр или запустить приложение и загрузить файл, следует воспользоваться функцией GetObject.

Если объект зарегистрировал себя как объект типа «единственный экземпляр», создается только один экземпляр этого объекта независимо от того, сколько раз выполнялась функция CreateObject.

Пример

В данном примере функция CreateObject используется для задания ссылки (

) в Excel. Ссылка используется для доступа к свойству «Видимый» в Excel, а затем используется метод выхода Excel, чтобы закрыть его. Наконец, выпустится сама ссылка.

Источник

CreateObject function

Creates and returns a reference to an ActiveX object.

Syntax

CreateObject(class, [ servername ])

The CreateObject function syntax has these parts:

Part Description
class Required; Variant (String). The application name and class of the object to create.
servername Optional; Variant (String). The name of the network server where the object will be created. If servername is an empty string («»), the local machine is used.

The class argument uses the syntax appname.objecttype and has these parts:

Part Description
appname Required; Variant (String). The name of the application providing the object.
objecttype Required; Variant (String). The type or class of object to create.

Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

To create an ActiveX object, assign the object returned by CreateObject to an object variable.

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. After an object is created, you reference it in code by using the object variable you defined. In the following example, you access properties and methods of the new object by using the object variable, ExcelSheet , and other Microsoft Excel objects, including the Application object and the Cells collection.

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name; for a share named «MyServerPublic,» servername is «MyServer.»

[!NOTE] > Refer to COM documentation (see _Microsoft Developer Network_) for additional information about making an application visible on a remote networked computer. You may have to add a registry key for your application.—>

The following code returns the version number of an instance of Excel running on a remote computer named MyServer :

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Example

This example uses the CreateObject function to set a reference ( xlApp ) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

CreateObject function (Visual Basic for Applications)

vblr6.chm1010851

vblr6.chm1010851

office

d887c3d3-5c60-09a1-6856-49f7c4cc05ba

12/11/2018

high

Creates and returns a reference to an ActiveX object.

Syntax

CreateObject(class, [ servername ])

The CreateObject function syntax has these parts:

Part Description
class Required; Variant (String). The application name and class of the object to create.
servername Optional; Variant (String). The name of the network server where the object will be created. If servername is an empty string («»), the local machine is used.

The class argument uses the syntax appname.objecttype and has these parts:

Part Description
appname Required; Variant (String). The name of the application providing the object.
objecttype Required; Variant (String). The type or class of object to create.

Remarks

Every application that supports Automation provides at least one type of object. For example, a word processing application may provide an Application object, a Document object, and a Toolbar object.

To create an ActiveX object, assign the object returned by CreateObject to an object variable.

' Declare an object variable to hold the object 
' reference. Dim as Object causes late binding. 
Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. After an object is created, you reference it in code by using the object variable you defined. In the following example, you access properties and methods of the new object by using the object variable, ExcelSheet, and other Microsoft Excel objects, including the Application object and the Cells collection.

' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True
' Place some text in the first cell of the sheet.
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
' Save the sheet to C:test.xls directory.
ExcelSheet.SaveAs "C:TEST.XLS"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit
' Release the object variable.
Set ExcelSheet = Nothing

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:

Dim xlApp As Excel.Application 
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.WorkSheet
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

Call MySub (CreateObject("Excel.Application"))

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name; for a share named «MyServerPublic,» servername is «MyServer.»

The following code returns the version number of an instance of Excel running on a remote computer named MyServer:

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application", "MyServer")
Debug.Print xlApp.Version

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

[!NOTE]
Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

Example

This example uses the CreateObject function to set a reference (xlApp) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.

Dim xlApp As Object    ' Declare variable to hold the reference.
    
Set xlApp = CreateObject("excel.application")
    ' You may have to set Visible property to True
    ' if you want to see the application.
xlApp.Visible = True
    ' Use xlApp to access Microsoft Excel's 
    ' other objects.
    ' Closes the application using the Quit method
xlApp.Quit    

See also

  • Functions (Visual Basic for Applications)

[!includeSupport and feedback]

Return to VBA Code Examples

This article will show you how to use the Create Object method in VBA.

VBA is an Object Orientated Language – it uses procedures to control and create Objects.

Create Object

We can use the Create Object method to create an Object in a Microsoft Office application.  For example, if we are writing VBA code in Excel, and wish to open a copy of Word, we can use the Create Object method to create a new instance of Word.

For example:

Sub CreateWordInstance()
  Dim wdApp As Object
  Set wdApp = CreateObject("Word.Application")
  wdApp.Visible = True
End Sub

Similarly, we can create a new instance of PowerPoint or Access.

Sub CreatePowerPointApplication
  Dim ppApp as Object 
  Set ppApp = CreateObject("PowerPoint.Application")
  ppApp.Visible = True 
End Sub

We can also use Create Object to create objects other than the Application Object.  We can use it to create an Excel Sheet for example.

Sub CreateExcelSheet()
  Dim xlSheet As Object
  Set xlSheet = CreateObject("Excel.Sheet")
  xlSheet.Application.Visible = True
  xlSheet.Application.Range("A2") = "Good morning"
  Set xlSheet = Nothing
End Sub

However, this actually creates a new instance of Excel – it does not create the sheet in the instance that is already open.  For that reason, we have to set Application of the new sheet (ie: the new instance of Excel) to Visible in order to see the object.

In all of the examples above, we are using Late Binding – hence we declare the variables as Objects.  We can also use Early Binding by setting a reference to Word or PowerPoint in our VBA Project and then writing the Sub Procedure as shown below. To understand more about Late and Early binding, click here.

Firstly for Early Binding, within the VBE, we set a reference to Microsoft Word.

In the Menu bar, select Tools > References and scroll down to find the reference to the Microsoft Word 16.0 Object Library.

VBACreateObject Reference

Make sure the reference is checked, and then click OK.

NOTE: the version might not be 16.0, it all depends on what version of Microsoft Office you are running on your PC!

Now, we declare the Object using Early Binding – this means that, instead of declaring the wdApp as an Object, we declare it as a Word.Application.   The rest of the code is the same as when we used Late Binding above.

Sub CreateWordInstance() 
  Dim wdApp As New Word.Application
  Set wdApp = CreateObject("Word.Application") 
  wdApp.Visible = True 
End Sub

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!
vba save as

Learn More!

Objects are created from the class. If we take some real-life examples then let’s say a Dog is a class where it has its properties and methods like breed, age, and color whereas we can say Dog1 or Dog2 are objects having different breeds, ages, and colors. We can simply say the object is a grouping of data and functions. In VBA “Collection” is a class where we can create its object using “New” so that we can use its in-built methods like Add, Remove and Count. 

Object Components

Properties 

It is used to read or write a value where we can read the value from the object or we can write a value to the object but we can’t update the value in the object

Writing-and-reading-value

Methods

Some actions are performed by this method in the object collection is an object where we can perform many actions with the help of methods like Add, Count, and Remove. The following code is shown to add a value in the collection object using the “Add” method

Adding-value

Events

When an event occurs a function executes called events in the object. Events are like clicking a button, opening a workbook, or activating a worksheet. The following code is shown to display a message by “MsgBox” after an event Workbook_Open() takes place

code-for-displaying-message

Creating a VBA Object

To create an object we have to follow three steps

  1. A variable should be declared
  2. A new object should be created 
  3. The new object should be assigned to the variable

These three steps can be done in many ways which are discussed in the following,

Using Dim with New

In a single line, we can declare, create and assign the object. We can’t use the declare variable to create multiple objects. In the following code, we are creating an object of Collection and storing it in a variable “Collection_12”.

Code-to-create-object-of-collection

Using Set with New

We are declaring the variable to store the object using Dim in one line than in another line we can create and assign the object.

Declaring-variable

Using Let 

It is used to assign a value to the variable of an inbuilt object like String, Long, Integer, or Double. Let is used to store the value whereas set is used to store the address. In the following code, a variable is assigned by a value and that variable is a data type of string which is also an inbuilt object.

Using-let-to-store-object

When New is Not Required

When we want to create an object of a workbook or worksheet at that time we usually don’t use New without using New we can create an object.

Creating-an-object

In VBA there are four important objects,

  • Application Object
  • Workbook Object
  • Worksheet Object
  • Range Object
  • Shape Object

Application Object

The entire Excel Application is referred to as Application Objects. The application object contains the workbook object which we can use to manipulate the data present in the application object. The following code is to change the color of the font to red in the application.

Code-to-change-color

Workbook Object

All worksheets which are currently open in excel are referred to as workbook objects. We can use the workbook object to add a sheet to the workbook or to save the existing sheets in the workbook.

Workbook-to-save-existing-sheet

Worksheet Object

It refers to the present sheet of excel which is in the active state, we can use it to manipulate the active sheet. In the following code, we will change the orientation of the active sheet to the landscape.

Changing-orientation-of-the-active-sheet

Range Object

It is used to refer to a group of cells or a single cell so that we can manipulate it according to our desire. In the following code, we are selecting a range of cells from A1 to C6.

Selecting-range-of-cells

Shape Object

It is used to add a shape or to change the dimension of the active sheet. In the following code, a rounded rectangle shape is added in the active sheet where the value of the rounded portion of the rectangle will be 100 and 200 in the top right and left part whereas the value of the bottom right and left will be 50.

Code-to-change-dimension

Excel VBA Custom Classes & Objects, Class Modules, Custom Events

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

Contents:

Custom Classes and Objects

Custom Class Events

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

In vba you can create your own custom objects by defining classes & inserting class modules. You can also create your own custom class events, in addition to Excel’s own inbuilt event procedures. In this section we explain how to create custom objects by inserting a class module and how to create your own custom events in a class.

Custom Classes and Objects

In vba you can create your own custom objects by defining classes. Classes act as templates for new objects. The custom object is used to store, process and make data available. A Class contains data and code — data can be accessed with properties (viz. Name property) and the code is referred to as methods (which are defined as Subs and Functions in VBA). Classes are integral to the Object-Oriented Programming (OOP) language. A class is created by inserting a Class Module (in your VBA project) to which you give a name. A Class Module allows you to create your own objects having their own properties and methods much like other objects such as range, worksheet, chart, etc. The Class Module has its own set of vba code (which includes variables, constants and procedures), which defines its properties and methods. The properties of the class object are manipulated in a Class Module with Property procedures which use the Property Let, Property Get, and Property Set statements. To access the properties and methods of the class object from a procedure in a code module, you declare an object variable of the class’s type in that procedure.

You can do all vba programming without creating custom objects which do not really increase code functionality. However, using custom objects makes complex coding look simpler by having related code in one place, makes coding self-documenting with appropriately named classes, properties & methods, and this helps in debugging and reusing code.

Insert a Class Module:

In Visual Basic Editor (VBE), click Insert in the menu bar and then click Class Module. Alternatively, in the Project Explorer in VBE, right click on the VBA Project name or any object or item under it, click Insert and then click Class Module. Or, on the Standard Tool bar in VBE, click the Insert button and then click Class Module. This creates a blank class with the name Class1. To remove or delete a Class Module, right click after selecting it in the Project Explorer in VBE, and then click on Remove.

Name a Class Module:

The name of the selected Class Module appears to the right of (Name) in the Properties Window in VBE, and can be changed therein.

Instancing Property of a Class Module:

The Instancing property of a Class Module is set to Private by default which does not allow an external project from working with and using instances of that class. Set the Instancing property to PublicNotCreatable to allow external projects, with a reference set to the project containing the defined class, to access and use instances of the defined class. Note that the setting of PublicNotCreatable still does not allow the external project to instantiate (ie. create or call into existence) the class object or an instance of the class, which can be instantiated only by the project which contains the definition of the class. Note that the external project can use an instance of the defined class if the referenced project has already created that instance.

Instantiate a Class Object:

As already mentioned, in vba you can create your own custom objects by defining classes. A class is created by inserting a Class Module. To access the properties and methods of the class object from a procedure in a code module, you need to create a new instance of the class object ie. instantiate  (ie. create or call into existence) an instance of the class. Note that multiple number of instances of a class object can be created. There are two ways of doing this, one with a two-line code or alternatively with a single-line code.

Two-line code to instantiate an instance of a class:

Use the Dim statement to create a variable (iStudent) and define it as a reference to the class (clsStudent):

Dim iStudent As clsStudent

Create a new object reference by using the New keyword. Mention the name of the class (clsStudent) you want to instantiate, after the New keyword:

Set iStudent = New clsStudent

Alternate single-line code to instantiate an instance of a class:

In this case the clsStudent object gets instantiated only when the class method is first called ie. iStudent gets instantiated only when first used.

Dim iStudent As New clsStudent

Create Class Properties:

One way to create a class property is by declaring a Public Variable in the Class Module, and this property will be read-write. The other way to create a class property is by using Property Procedures ie. create a private variable to hold values and use property statements (viz. Property Let, Property Set and Property Get). Creating properties using a Public Variable, though simple, may not usually be preferable because it is not flexible. Using property statements will enable to set a read-only or write-only property in addition to read-write, whereas using a public variable will create only read-write properties. Further, using property statements you can execute code to calculate values as properties whereas using a public variable will not allow use of code to set or return the value of a property. For example, in case of an Area property, the area of a rectangle changes per its length-width and in case the length-width is dynamic it should not be stored as a fixed value.

Create methods in a Class Module: In addition to properties, objects can also have one or more methods. A method is defined as Subs and Functions in VBA and is created with Sub-routine and Function procedures. A method is a sub-procedure containing a set of codes which perform an action or an operation on the data within the class, or a function containing a set of codes which returns a value after performing an operation. In a Class Module, only if the method is declared Public can it be called from an instance of this class, else if a method is declared Private it can be called only from other methods within the class. Note, that by default a procedure is Public if the Private or Public keywords are not specified.

Using Property Procedures to Create Properties:

Property Procedure is a set of vba codes that creates and manipulates custom properties for a class module. A Property procedure is declared by a Property Let,  Property Get or Property Set statement and ends with an End Property statement. Property Let (write-only property) is used to assign a value to a property and Property Get (read-only property — which can only be returned but not set) returns or retrieves the value of a property. Property Set (write-only property) is used to set a reference to an object. Property procedures are usually defined in pairs, Property Let and Property Get OR Property Set and Property Get. A Property Let procedure is created to allow the user to change or set the value of a property, whereas the user cannot set or change the value of a read-only property (viz. Property Get).

A property procedure can do whatever can be done within a vba procedure like performing an action or calculation on data. A Property Let (or Property Set) procedure is an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Get procedure or a Function but does not return a value like them. A Property Get procedure is also an independent procedure which can pass arguments, perform actions as per a set of codes and change the value of its arguments like a Property Let (or Property Set) procedure, and can be used similar to a Function to return the value of a property.

A Property Get declaration takes one argument less than in the associated Property Let or Property Set declaration and the Property Get declaration should be of the same data type as the data type of the last argument in the associated Property Let or Property Set declaration. The Property Get declaration will use the same property name as used in the associated Property Let or Property Set declaration.

A Property Let procedure can accept multiple arguments, and in this case the last argument contains the value to be assigned to the property. This last argument in the argument list is the property value set by the calling procedure. The name and data type of each argument in a Property Let procedure and its corresponding Property Get procedure should be the same, except for the last argument in the Property Let procedure which is additional. All arguments before the last argument are passed to the Property Let procedure. In the case of a Property Let procedure with a single argument (at least one argument is required to be defined), this argument contains the value to be assigned to the property and is the value set by the calling procedure. In this case the Property Get procedure will have no argument. It is not a usual practice to pass multiple arguments in property procedures and sub-procedures or Functions are used for this.

A Property Set procedure can accept multiple arguments, and in this case the last argument contains the actual object reference for the property. All arguments before the last argument are passed to the Property Set procedure. In the case of a Property Set procedure with a single argument (at least one argument is required to be defined), this argument contains the object reference for the property. The data type of the last argument or the single argument must be an Object type or a Variant.

The Property Set procedure is similar to and a variation of the Property Let procedure and both are used to set values. A Property Set procedure is used to create object properties which are actually pointers to other objects, whereas a Property Let procedure sets or assigns values to scalar properties like string, integer, date, etc. Using the Property Set statement enables Properties to be represented as objects.

Below is the syntax for the 3 property procedure declarations.

Property Get:

Property Get PropertyName(argument_1, argument_2, …, argument_n) As Type

Property Let:

Property Let PropertyName(argument_1, argument_2, …, argument_n+1)

Property Set:

Property Set PropertyName(argument_1, argument_2, …, argument_n+1)

Examples

Example 1 — Create Class Properties by using Property Procedures. Refer Images 1a & 1b. For live code, click to download excel file.

Insert Code in Class Module named clsStudent:

‘Example — Create Class Properties by using Property Procedures:
Private strStuName As String
Private dblStuMarks As Double

Public Property Let Name(strN As String)
‘declare the property procedure Public so that it can be called from an instance of this class in another module.
‘In the case of a Property Let procedure with a single argument (at least one argument is required to be defined), this argument contains the value to be assigned to the property and is the value set by the calling procedure. In this case the Property Get procedure will have no argument. A Property Let procedure is created to allow the user to change or set the value of a property, whereas the user cannot set or change the value of a read-only property (viz. Property Get).

strStuName = strN

End Property

Public Property Get Name() As String
‘returns the Name property

Name = strStuName

End Property

Public Property Let Marks(iMarks As Double)
‘assigns the Marks property

dblStuMarks = (iMarks / 80) * 100

End Property

Public Property Get Marks() As Double
‘returns the Marks property

Marks = dblStuMarks

End Property

Public Function Grade() As String
‘Create a Method within a Class — declare the method Public so that it can be called from an instance of this class in another module.

Dim strGrade As String

If dblStuMarks >= 80 Then

strGrade = «A»

ElseIf dblStuMarks >= 60 Then

strGrade = «B»

ElseIf dblStuMarks >= 40 Then

strGrade = «C»

Else

strGrade = «Fail»

End If

Grade = strGrade

End Function

Insert Code in a Standard Code Module:

Sub clsStudentRun()
‘this procedure instantiates an instance of a class, sets and calls class properties:

‘use the Dim statement to create a variable and define it as a reference to the class.
Dim iStudent As clsStudent

‘a new object reference is created by using the New keyword. Mention the name of the class you want to instantiate, after the New keyword.
‘following code line (together with the above Dim statement, it is a two-line code to instantiate an instance of a class), instantiates the clsStudent object:
Set iStudent = New clsStudent

‘alternate single-line code to instantiate an instance of a class, however in this case the clsStudent object gets instantiated only when the class method is first called, ie. iStudent gets instantiated only when first used:
‘Dim iStudent As New clsStudent

‘sets the Name property in the clsStudent object to be the string «Peter», and passes this data to the strN variable in the Name property:
iStudent.Name = «Peter»

‘call the Name property in the clsStudent object
MsgBox iStudent.Name

‘sets the Marks property in the clsStudent object to the value 45, and passes this data to the iMarks variable in the Marks property:
iStudent.Marks = 45

‘call the Marks property in the clsStudent object
MsgBox iStudent.Marks

‘call the Grade function from the clsStudent object:
MsgBox iStudent.Grade

MsgBox iStudent.Name & » has got » & iStudent.Marks & » percent marks with a Grade » & iStudent.Grade

End Sub

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

Example 2 — Create Class Properties by using Property Procedures, Property Let procedure accepting multiple arguments. For live code, click to download excel file.

Insert Code in Class Module named clsRectangle:

‘Example — Create Class Properties by using Property Procedures, Property Let procedure accepting multiple arguments.
Private dblA As Double

Public Property Let Area(lngth As Double, wdth As Double, ar As Double)
‘A Property Let procedure can accept multiple arguments, and in this case the last argument contains the value to be assigned to the property. This last argument in the argument list is the property value set by the calling procedure. The name and data type of each argument in a Property Let procedure and its corresponding Property Get procedure should be the same, except for the last argument in the Property Let procedure which is additional. All arguments before the last argument are passed to the Property Let (& Property Get) procedure.

‘In the case of a Property Let procedure with a single argument (at least one argument is required to be defined), this argument contains the value to be assigned to the property and is the value set by the calling procedure. In this case the Property Get procedure will have no argument.

‘It is not a usual practice to pass multiple arguments in property procedures and sub-procedures or Functions are used for this.

dblA = ar

MsgBox «Arguments received — lngth: » & lngth & «, wdth: » & wdth & «, ar: » & ar

End Property

Public Property Get Area(lngth As Double, wdth As Double) As Double

Area = dblA

End Property

Insert Code in a Standard Code Module:

Sub clsRectangleRun()
‘This procedure instantiates an instance of a class, sets and calls class properties, passing multiple arguments to Property Let procedure:

Dim l As Double
Dim w As Double

Dim rect As New clsRectangle

l = InputBox(«Enter Length of rectangle»)
w = InputBox(«Enter Width of rectangle»)

‘setting the property value — passes this data to the ar variable in the Area property:
rect.Area(l, w) = l * w

‘accessing the Area property:
a = rect.Area(l, w)

MsgBox «Area of Rectangle with length » & l & «, width » & w & «, is » & a

End Sub

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

Example 3 — Create Read-Only Class Property with only the PropertyGet_EndProperty block. For live code, click to download excel file.

Insert Code in Class Module named clsRectArea:

‘Example — Create Read-Only Class Property with only the PropertyGet_EndProperty block.
Private dRectL As Double
Private dRectW As Double

Public Property Let Length(l As Double)

dRectL = l

End Property

Public Property Get Length() As Double

Length = dRectL

End Property

Public Property Let Width(w As Double)

dRectW = w

End Property

Public Property Get Width() As Double

Width = dRectW

End Property

Public Property Get rArea() As Double
‘Read-Only property with only the PropertyGet_EndProperty block and no PropertyLet_EndProperty (or PropertySet_EndProperty) block.

rArea = Length * Width

End Property

Insert Code in a Standard Code Module:

Sub clsRectAreaRun()
‘This procedure instantiates an instance of a class, sets and calls class properties.

Dim a As Double
Dim b As Double

Dim areaRect As New clsRectArea

a = InputBox(«Enter Length of rectangle»)
b = InputBox(«Enter Width of rectangle»)

areaRect.Length = a
areaRect.Width = b

MsgBox areaRect.rArea

End Sub

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

Example 4 — Using Property Set statement to set a reference to an object.

A Property Set procedure is used to create object properties which are actually pointers to other objects. Refer Images 2a, 2b & 2c. For live code, click to download excel file.

Insert Code in Class Module named clsCar:

‘Example — Using Property Set statement to set a reference to an object. A Property Set procedure is used to create object properties which are actually pointers to other objects.

‘declare a private variable (ie. varCar) to store a reference to the clsMotorCars object:
Private varCar As clsMotorCars

Public Property Set Car(objCar As clsMotorCars)
‘The Property Set statement sets a reference to an object, and assigns Car to an object.

‘create an object variable (ie. varCar) and point it to the clsMotorCars object passed to the procedure:
Set varCar = objCar

End Property

Public Property Get Car() As clsMotorCars

‘return the object variable (ie. varCar) created by the Property Set procedure:
Set Car = varCar

End Property

Insert Code in Class Module named clsMotorCars:

‘Create Class Properties by using Property Procedures:
Private strColor As String
Private strName As String
Private dMG As Double

Property Let Color(clr As String)

strColor = clr

End Property

Property Get Color() As String

Color = strColor

End Property

Property Let Name(nm As String)

strName = nm

End Property

Property Get Name() As String

Name = strName

End Property

Property Let Mileage(milesGallon As Double)

dMG = milesGallon

End Property

Property Get Mileage() As Double

Mileage = dMG

End Property

Function FuelBudget(FuelCost As Double, Distance As Double) As Double

FuelBudget = (Distance / Mileage) * FuelCost

End Function

Insert Code in a Standard Code Module:

Sub propSetCars()
‘Using Property Set statement to set a reference to an object. A Property Set procedure is used to create object properties which are actually pointers to other objects.

Dim dDist As Double
Dim dCost As Double

‘instantiate as a clsCar object ie. create a new instance of the clsCar object. A new object reference is created by using the New keyword.
Dim ownCar As clsCar
Set ownCar = New clsCar

‘Car has been instantiated as a clsMotorCars object (note that Car is a property of the ownCar object). See below how to access the properties & methods of clsMotorCars object:
Set ownCar.Car = New clsMotorCars

‘enter property values:
ownCar.Car.Color = «Yellow»
ownCar.Car.Name = «Ford»
ownCar.Car.Mileage = 50
dDist = InputBox(«Enter Distance in miles, covered by car in a month»)
dCost = InputBox(«Enter Cost of Fuel per gallon»)

‘return values from properties & methods of clsMotorCars object:
MsgBox «Car Color is » & ownCar.Car.Color
MsgBox «Car Model is » & ownCar.Car.Name
MsgBox «Gives a Mileage of » & ownCar.Car.Mileage & » miles per gallon»
‘call the FuelBudget function:
MsgBox «$» & ownCar.Car.FuelBudget(dDist, dCost) & » is the monthly cost of fuel»

End Sub

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

Example 5 — Using Property Set statement to set a reference to a Range object. For live code, click to download excel file.

Insert Code in Class Module named clsSetRange:

‘Example — Using Property Set statement to set a reference to a Range object:
Private intColor As Integer
Private strName As String
‘declare a private variable (ie. rngV) to store a reference to the Range object:
Private rngV As Range

Public Property Set activeRange(oRng As Range)

‘create an object variable (ie. rngV) and point it to the Range object passed to the procedure:

Set rngV = oRng

End Property

Public Property Get activeRange() As Range

Set activeRange = rngV

End Property

Property Let Name(nam As String)

strName = nam

End Property

Property Get Name() As String

Name = strName

End Property

Property Let Color(clr As Integer)

intColor = clr

End Property

Property Get Color() As Integer

Color = intColor

End Property

Sub methodColor()

activeRange.Interior.ColorIndex = Color

End Sub

Insert Code in a Standard Code Module:

Sub clsSetRangeRun()
‘Example — Using Property Set statement to set a reference to a Range object.:

‘Instantiate as a clsRange object ie. create a new instance of the clsSetRange object. A new object reference is created by using the New keyword.
Dim rngActive As clsSetRange
Set rngActive = New clsSetRange

‘Set activeRange property (which is an object property) of clsSetRange object to ActiveCell, and pass this data to the oRng variable in the activeRange property:
Set rngActive.activeRange = ActiveCell

‘enter ColorIndex, value 1 to 56:
‘3 for red, 4 for green & 5 for blue, ….
rngActive.Color = 5

If rngActive.Color < 1 Or rngActive.Color > 56 Then

MsgBox «Error! Enter a value for ColorIndex between 1 and 56»

Exit Sub

End If

‘call sub-procedure named methodColor:
rngActive.methodColor

MsgBox «Interior color, ColorIndex » & rngActive.Color & «, entered in cell » & rngActive.activeRange.Address

End Sub


Custom Class Events

You can create your own class events also. Events are actions performed, or occurences, which trigger a VBA macro. A VBA code is triggered when an event occurs such as, clicking on a button, opening the workbook, selecting a cell or changing cell selection in a worksheet, and so on. Excel also has its own Event Procedures which 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 as «Private Sub Worksheet_Change(ByVal Target As Range)». When content of a worksheet cell changes, VBA calls the Worksheet_Change event procedure and runs the code it contains. Here we explain how to create your own custom events in a class.

Define a Custom Event:

The first step is to declare the event in the declaration section of the class. Use the Event keyword to define a custom event in a class module. It can have any number of arguments, and the event declaration should be Public to make it visible outside the object module. Note that you can declare and raise Events only within object modules (viz. ThisWorkbook module, Sheet modules — worksheets and chart sheets, UserForm modules and Class modules), and not from a standard code module.

Raise an Event:

After declaring an event, use a RaiseEvent Statement to trigger the declared event. The event procedure runs when an event is raised or triggered. The event is raised in a public procedure within the class module where it is declared, using the Event keyword. The RaiseEvent statement passes values for the event’s arguments, which also get passed to the event procedure that runs on raising the event.

External Code to Raise the Event:

However we need an external code to call the public procedure in the class module, which raises the event. This external code determines when the event will be raised by which the event procedure runs.

Create an Event Procedure:

Use the WithEvents keyword to declare an object variable of the custom class (in which the custom event is defined) type. By declaring this object variable, the instance of the custom class which this object variable points to will respond to the event by adding the object to the events list in the Code window. Only variables declared at module level can be used with the WithEvents keyword. Also variables can be declared using the WithEvents keyword only in object modules and not a standard code module. After the object variable declaration, the event procedure stub can be created similar to standard vba procedures — the object variable will be displayed in the Object drop-down list and all its events are listed in the Procedure drop-down list.

Examples

Example 6 — Create a Custom Event:- use a Worksheet_Change procedure to trigger the custom event. Refer Images 3a & 3b. For live code, click to download excel file.

Insert Code in Class Module named clsRange:

‘Example of Creating a Custom Event — use a Worksheet_Change procedure to trigger the custom event:
Private rngVar As Range
Private intColor As Integer
Private strName As String
‘Event declaration: Use the Event keyword to define a custom event (ie. CellSelect event) in a class module (ie. clsRange class). It can have any number of arguments, and the event declaration should be Public to make it visible outside the object module.
Public Event CellSelect(cell As Range)

Public Property Set selectedRange(objRng As Range)

Set rngVar = objRng
‘Trigger the event: the RaiseEvent statement executes & raises the CellSelect event and passes values for its arguments. Note that using the RaiseEvent keyword is similar to using the Call keyword used to call & execute a procedure in vba.
RaiseEvent CellSelect(rngVar)

End Property

Public Property Get selectedRange() As Range

Set selectedRange = rngVar

End Property

Property Let Name(nm As String)

strName = nm

End Property

Property Get Name() As String

Name = strName

End Property

Property Let Color(clr As Integer)

intColor = clr

End Property

Property Get Color() As Integer

Color = intColor

End Property

Sub methodColor()

selectedRange.Interior.ColorIndex = Color

End Sub

Insert Code in a Worksheet (sheet named ‘Sheet1’) Module:

‘Use the WithEvents keyword to declare an object variable (rng) of type clsRange. By declaring this object variable, the instance of the clsRange class which this object variable points to will respond to the event by adding the object to the events list in the Code window. Only variables declared at module level can be used with the WithEvents keyword.
‘After the variable declaration, the event procedure stub can be created similar to standard vba procedures — rng will be displayed in the Object drop-down list and all its events are listed in the Procedure drop-down list.
Private WithEvents rng As clsRange

Private Sub rng_CellSelect(cell As Range)
‘this is an event procedure, consisting of a set of codes, which runs on raising the CellSelect event.

‘enter ColorIndex, value 1 to 56:
‘3 for red, 4 for green & 5 for blue, ….
rng.Color = 4

If rng.Color < 1 Or rng.Color > 56 Then

MsgBox «Error! Enter a value for ColorIndex between 1 and 56»

Exit Sub

End If

rng.Name = «FirstCell»

‘call sub-procedure called methodColor:
rng.methodColor

‘note that rng.selectedRange & rng.Color values have been assigned, because they will lose values while executing below code:
Dim i As Integer
i = rng.Color

rng.selectedRange.Select
Selection.Offset(0, 1).Value = «Cell Name: « & rng.Name
Selection.Offset(0, 2).Value = «Cell Address: « & Selection.Address
Selection.Offset(0, 3).Value = «Cell Interior ColorIndex: « & i
Selection.Offset(0, 4).Value = «Cell Content: « & Selection.Value

End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
‘this worksheet change procedure calls the selectedRange public procedure of the clsRange object.

On Error GoTo ErrorHandler  ‘Enable error-handling routine for any run-time error

‘Instantiate as a clsRange object ie. create a new instance of the clsRange object. A new object reference is created by using the New keyword.
Set rng = New clsRange

‘CHANGE CONTENTS OF CELL A1 IN SHEET1 TO RUN THIS PROCEDURE:
‘Set selectedRange property (which is an object property) of clsRange object to ActiveCell, and pass this data to the objRng variable in the selectedRange property:
If Target.Address = Range(«A1»).Address Then

Set rng.selectedRange = Target

Else

Exit Sub

End If

ErrorHandler:
  Application.EnableEvents = True  ‘EnableEvents is changed back to True on any error

End Sub

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

Example 7 — Create a Custom Event:- initialization of the UserForm triggers the custom event. Refer Images 4a, 4b & 4c. For live code, click to download excel file.

Insert Code in Class Module named clsTextBox:

‘Example of Creating a Custom Event — initialization of the UserForm triggers the custom event:
Private tb As MSForms.TextBox
Private strSeq As String
‘Event declaration: Use the Event keyword to define a custom event (ie. eTxtBx event) in a class module (ie. clsTextBox class). It can have any number of arguments, and the event declaration should be Public to make it visible outside the object module.
Public Event eTxtBx(objTxtBx As MSForms.TextBox)

Public Property Set setTxtBx(objTxtBx As MSForms.TextBox)

Set tb = objTxtBx
‘Trigger the event: the RaiseEvent statement executes & raises the eTxtBx event and passes values (TextBox object) for its arguments (objTxtBx). Note that using the RaiseEvent keyword is similar to using the Call keyword used to call & execute a procedure in vba.
RaiseEvent eTxtBx(tb)

End Property

Public Property Get setTxtBx() As MSForms.TextBox

Set setTxtBx = tb

End Property

Property Let Sequence(tbSeq As String)

strSeq = tbSeq

End Property

Property Get Sequence() As String

Sequence = strSeq

End Property

Insert a UserForm, insert 2 textBox (TextBox1 & TextBox2) and a CommandButton (CommandButton1) within the Form. Insert Code in the UserForm Module:

‘Use the WithEvents keyword to declare an object variable (tx) of type clsTextBox. By declaring this object variable, the instance of the clsTextBox class which this object variable points to will respond to the event by adding the object to the events list in the Code window. Only variables declared at module level can be used with the WithEvents keyword.
‘After the variable declaration, the event procedure stub can be created similar to standard vba procedures — tx will be displayed in the Object drop-down list and all its events are listed in the Procedure drop-down list.
Private WithEvents tx As clsTextBox
Private sq1 As String, sq2 As String

Private Sub CommandButton1_Click()
‘using the excel built-in event Click: procedure runs on clicking the command button:

‘copying the contents of TextBox1 to all other TextBoxes and changing the BackColor of these TextBoxes to red:
Dim objControl As Control
For Each objControl In Me.Controls

If TypeName(objControl) = «TextBox» Then

If Not objControl.Name = «TextBox1» Then

objControl.Value = «copied: « & tx.setTxtBx.Value

objControl.BackColor = vbRed

End If

End If

Next

MsgBox «text copied from the » & sq1 & » to the » & sq2

   

End Sub

Private Sub TextBox1_Change()
‘using the excel built-in event Change: procedure runs on change in TextBox contents:

If tx.setTxtBx.Value = «» Then

tx.setTxtBx.BackColor = vbYellow

Else

tx.setTxtBx.BackColor = vbGreen

End If

End Sub

Private Sub tx_eTxtBx(objTxtBx As MSForms.TextBox)
‘this is an event procedure, consisting of a set of codes, which runs on raising the eTxtBx event.

tx.setTxtBx.BackColor = vbYellow

With Me.TextBox1

tx.Sequence = «First TextBox»

sq1 = tx.Sequence

End With

    With Me.TextBox2

tx.Sequence = «Second TextBox»

sq2 = tx.Sequence

End With

End Sub

Private Sub UserForm_Initialize()
‘initialization of the userform calls the setTxtBx public procedure of the clsTextBox object.

‘Instantiate as a clsTextBox object ie. create a new instance of the clsTextBox object. A new object reference is created by using the New keyword.
Set tx = New clsTextBox

‘Set setTxtBx object property of clsTextBox object, and pass the TextBox object (Me.TextBox1) to the objTxtBx variable in the setTxtBx property:
Set tx.setTxtBx = Me.TextBox1

   
End Sub

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

Example 8 — Create a Custom Event:- use the WithEvents keyword, within the class module, to declare an object variable (Initialize UserForm to start).

For live code, click to download excel file.

Insert Code in Class Module named clsComboBox:

‘Example of Creating a Custom Event — use the WithEvents keyword, within the class module, to declare an object variable:
‘Use the WithEvents keyword to declare an object variable (cBox) of type MSForms.ComboBox. By declaring this object variable here, the excel built-in events associated with this object variable will respond, by adding the object to the events list in the Code window.
Public WithEvents cBox As MSForms.ComboBox

Public Sub setComboBox(objCbx As MSForms.ComboBox)
‘On userform initialization, the ComboBox object (objCbx) is passed to this procedure. This procedure is declared public to make it accessible from outside the class module.

‘ComboBox object (objCbx) is assigned to the object variable (cBox):
Set cBox = objCbx

End Sub

Public Sub cBox_AddItem(strItem As String, Cancel As Boolean)
‘This procedure is declared public to make it accessible from outside the class module. Clicking the command button passes the value for strItem argument, and runs this procedure.

‘adds item to ComboBox list, unless AddItem event is cancelled:
If Cancel = False Then

cBox.AddItem strItem

End If

‘changes BackColor of ComboBox after adding an item:
If strItem <> «» Then
cBox.BackColor = vbGreen
End If

End Sub

Private Sub cBox_Change()
‘using the excel built-in event of Change, this procedure runs when the ComboBox text changes.

‘if ComboBox is blank, its BackColor will change to white:
If cBox.Value = «» Then

cBox.BackColor = vbWhite

End If

End Sub

Insert a UserForm, insert a ComboBox (ComboBox1) and a CommandButton (CommandButton1) within the Form. Insert Code in the UserForm Module:

‘instantiate an instance (cB) of the class object (clsComboBox):
Private cB As New clsComboBox

Private Sub CommandButton1_Click()

‘enter item in the text area of the ComboBox, which you want to add in ComboBox:
Dim strTxt As String
strTxt = cB.cBox.Text

Dim Cancel As Boolean

c = MsgBox(«Do you confirm adding the item in ComboBox?», vbYesNo)
If c = vbNo Then

Cancel = True

End If

‘call the class method cB.cBox_AddItem and pass value and Boolean variable:
Call cB.cBox_AddItem(strTxt, Cancel)

End Sub

Private Sub UserForm_Initialize()

‘call the class method (setComboBox) and pass ComboBox object for its argument’s (objCbx) value:
cB.setComboBox Me.ComboBox1

End Sub

As the name suggests, the CreateObject function is used to create objects. 

But why do we use CreateObject method or function if we can directly create an object using the new keyword? 

Well, that’s a valid question and we have a fitting answer. 

The creation of an object using the CreateObject is called Late Binding. In late binding the creation of objects happens on the run time. It does not need any references to be added. This makes the VBA code portable.

For example, if you create an application that deals with other applications and you use early binding by adding references and using the new keyword. Later you transfer that code to some other machine, then you will have to add the references on that machine too. But if you had used the CreateObject method for creating other application objects, you will not need to add the references on other machines, in case you transfer or share the code.

In this article we will learn about the CreateObject method using some examples.

Syntax of CreateObject Function:

Set object_name= CreateObject(classname as string,[servername])

classname as string: It is a required variable. It is a string that refers to the name of application and object type. The application name and class of the object to be created should be declared in AppName.ObjecType. For example, if I want an object of Word Application then i would write «Word.Application». We will see it in detail in examples later.

[servername]: It is an optional variable. It is a string of the name of the network server where the object will be created. If servername is an empty string («»), the local machine is used. We will not be using this in this chapter.

Now, that we know the basics of the CreateObject function let’s use them in some examples:

Example 1: Open Microsoft Word Application Using Excel VBA

So, if we wanted to use early binding, we would add references to word applications using Tools—>References menu.

And our code would look like this.

Sub OpenWordApp()


    Dim wordApp As New Word.Application

    Dim wordDoc As Document

    wordApp.Visible = True

    wordDoc = wordApp.Documents.Add


End Sub

The advantage of this code, that you get the assistance of intellensence of VBA and it shows you the available method and properties of the object you have created.It will work perfectly fine your system. But, if you share this code to someone else and they haven’t added the reference to the microsoft word library from tools, they will get an error.

To avoid this error, use the below code.

Sub OpenWordApp()

    Dim wordApp As Object

    

    Set wordApp = CreateObject("Word.Application")

    

    Dim wordDoc As Object

    wordApp.Visible = True

    Set wordDoc = wordApp.Documents.Add

End Sub

The above code will work perfectly fine on any machine. It is portable since we are doing late binding using CreateObject method to create the object.

Let’s see another example:

Example 2: Create Workbook Object Using CreateObject Function

If you are working with VBA for any amount of time, you must have created or added in workbooks using  the New keyword. In this example, we will do so using CreateObject.

Sub addSheet()

    

    ' Declare an object variable to hold the object

    ' reference. Dim as Object causes late binding.

    Dim ExcelSheet As Object

    Set ExcelSheet = CreateObject("Excel.Sheet")

    ' Make Excel visible through the Application object.

    ExcelSheet.Application.Visible = True

    ' Place some text in the first cell of the sheet.

    ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"

    ' Save the sheet to C:test.xls directory.

    ExcelSheet.SaveAs "C:TEST.XLS"

    ' Close Excel with the Quit method on the Application object.

    ExcelSheet.Application.Quit

    ' Release the object variable.

    Set ExcelSheet = Nothing

End Sub

So yeah guys, this is how you use the CreateObject method in VBA. Let’s discuss the benefits and shortcomings of it.

Advantages of CreateObject to create Object

The main advantage of the CreateObject is that it makes your code portable (when the object creation is the concern). You can share the code to anyone without worrying about if they have added the reference to the object program using or not.

Shortcoming of CreateObject

The shortcomings of CreateObject method are:

You need to know the structure of the Class you are going to use for object creation.

Once you have created the object, you are totally dependent on your memory for the methods and properties of objects, as VBA does not provide any intellisense to help you.

We can overcome the above shortcomings. I have a trick.

Whenever I write code that will be shared to others, I use the first method for creating objects (Adding references from tools). This helps me write the code faster. Once I finnish the VBA program and have tested it, I replace the New method with the CreateObject Method. This makes the code portable. You can use this trick.

So yeah guys, this is how you can use the CreateObject function to create objects in VBA. I hope I was able to explain everything. If you have any questions regarding this article or any other VBA related questions, ask me in the comments section below.

Related Articles:

Getting Started With Excel VBA UserForms| I will explain how to create a form in excel, how to use VBA toolbox, how to handle user inputs and finally how to store the user inputs. We will go through these topics using one example and step by step guide.

VBA variables in Excel| VBA stands for Visual Basic for Applications. It is a programming language from Microsoft. It is used with Microsoft Office applications such as MSExcel, MS-Word and MS-Access whereas VBA variables are specific keywords.

Excel VBA Variable Scope| In all the programming languages, we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers.

ByRef and ByVal Arguments | When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in the original argument.

Delete sheets without confirmation prompts using VBA in Microsoft Excel | Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.

Add And Save New Workbook Using VBA In Microsoft Excel 2016| In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc

Display A Message On The Excel VBA Status Bar| The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering.

Turn Off Warning Messages Using VBA In Microsoft Excel 2016| This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific values. Countif function is essential to prepare your dashboard.

How to use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

Like this post? Please share to your friends:
  • Criteria for distinguishing between phraseological units and free word groups
  • Creating number lines in word
  • Crisis is a greek word
  • Creating macros with excel
  • Crisis from greek word