This object was created in excel

Содержание

  1. Insert an object in your Excel spreadsheet
  2. CreateObject function
  3. Syntax
  4. Remarks
  5. Example
  6. See also
  7. Support and feedback
  8. Как работать с Excel через VBA или объектная модель Excel
  9. Объектная модель Excel
  10. Структура объектов
  11. Объекты и коллекции объектов
  12. Свойства объектов
  13. Методы объектов
  14. Приемы и лайфхаки
  15. Автоматическое заполнение кода по начальным символам
  16. Просмотр свойств и методов у объекта
  17. Явно указывайте тип переменных
  18. Быстрый просмотр справки
  19. Поиск по объектной модели

Insert an object in your Excel spreadsheet

You can use Object Linking and Embedding (OLE) to include content from other programs, such as Word or Excel.

OLE is supported by many different programs, and OLE is used to make content that is created in one program available in another program. For example, you can insert an Office Word document in an Office Excel workbook. To see what types of content that you can insert, click Object in the Text group on the Insert tab. Only programs that are installed on your computer and that support OLE objects appear in the Object type box.

If you copy information between Excel or any program that supports OLE, such as Word, you can copy the information as either a linked object or an embedded object. The main differences between linked objects and embedded objects are where the data is stored and how the object is updated after you place it in the destination file. Embedded objects are stored in the workbook that they are inserted in, and they are not updated. Linked objects remain as separate files, and they can be updated.

Linked and embedded objects in a document

1. An embedded object has no connection to the source file.

2. A linked object is linked to the source file.

3. The source file updates the linked object.

When to use linked objects

If you want the information in your destination file to be updated when the data in the source file changes, use linked objects.

With a linked object, the original information remains stored in the source file. The destination file displays a representation of the linked information but stores only the location of the original data (and the size if the object is an Excel chart object). The source file must remain available on your computer or network to maintain the link to the original data.

The linked information can be updated automatically if you change the original data in the source file. For example, if you select a paragraph in a Word document and then paste the paragraph as a linked object in an Excel workbook, the information can be updated in Excel if you change the information in your Word document.

When to use embedded objects

If you don’t want to update the copied data when it changes in the source file, use an embedded object. The version of the source is embedded entirely in the workbook. If you copy information as an embedded object, the destination file requires more disk space than if you link the information.

When a user opens the file on another computer, he can view the embedded object without having access to the original data. Because an embedded object has no links to the source file, the object is not updated if you change the original data. To change an embedded object, double-click the object to open and edit it in the source program. The source program (or another program capable of editing the object) must be installed on your computer.

Changing the way that an OLE object is displayed

You can display a linked object or embedded object in a workbook exactly as it appears in the source program or as an icon. If the workbook will be viewed online, and you don’t intend to print the workbook, you can display the object as an icon. This minimizes the amount of display space that the object occupies. Viewers who want to display the information can double-click the icon.

Источник

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.

Источник

Как работать с Excel через VBA или объектная модель Excel

Объектная модель Excel

Перед созданием своей первой программы в Excel необходимо разобраться в объектную модели приложения. Имея четкое понимания об объектной модели Excel вы сможете управлять практически всеми объектами, создавать/изменять листы, графики, отдельные файлы и многое другое. Возможно на первый взгляд она покажется довольно сложной, но не пугайтесь на конкретных примерах у вас сложится целостная картина.

Структура объектов

Проще всего рассматривать объектную модель как некое дерево или иерархическую структуру, так как каждый объект имеет свое ответвление. Кусочек этой структуры вы можете увидеть на рисунке далее.

Самый главный объект, вершина нашей структуры, это собственно само приложение Excel — объект Application. Какие объекты входят в Excel? правильно книги (файлы Excel), поэтому в объекте Application содержится коллекция из книг — объект Workbooks. Из чего состоят книги — из листов, диаграмм, соответственно внутри объекта Workbooks мы видим объект Worksheets и Charts. Идем дальше, лист в свою очередь состоит из строк, столбцов, ячеек это объекты Rows, Columns, Range.

Это, конечно, как вы понимаете только часть объектной модели Excel, мы перечислили только одни их самых основных объектов. Полное дерево объектов исчисляется сотнями объектов. Возможно она сейчас кажется сложной, не переживайте со временем вы начнете быстро в ней ориентироваться. Главное сейчас — это понять, что есть некие объекты, которые могут состоять из других объектов.

Объекты и коллекции объектов

Многие объекты, которые мы перечислили выше являются коллекциями. Коллекция — это группа однотипных объектов (или классов). Например Workbook s — это коллекция всех открытых в данный момент книг (объектов Workbook). А коллекция Worksheet s состоит из листов книги (объектов Worksheet), и так далее. Как правило все коллекции заканчиваются буквой S.

Давайте посмотрим, как обращаться к конкретным элементам коллекции в коде VBA.

Мы можем указать порядковый номер (начиная с единицы) элемента в коллекции. Worksheets(3) — в этом случае мы обращаемся к 3-му листу книги.

Мы также можем указать название листа в кавычках Worksheets(«Название листа»).

Аналогичным образом можно обратиться к конкретной книге Workbook(«Названием книги»).

Чтобы обратиться к объекту Excel (к листу, или ячейке) необходимо указать ссылку на этот объект, перечислив полный путь к нему в соответствии с объектной моделью.

Например, для ячейки A1 полная ссылка будет выглядеть следующим образом:

На самом деле полный путь писать не обязательно. Application — можно практически всегда не указывать. Workbooks(«Название книги») — можно не указывать, если необходимо обратиться к ячейке из активной книги, а Worksheets(«Название листа») можно не писать в случае если код должен выполнять действия на активном листе. Т.е. в можно упростить до:

Но всегда имейте ввиду, что это будет ячейка на активном листе.

Свойства объектов

Все объекты имеют свойства и методы. Например, объект Range (диапазон ячеек) имеет свойство Value, в котором содержится значение.

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

А следующий код присвоит свойству Value новое значение 12345.

Протестируйте эти функции в своем файле.

Кстати, есть свойства объектов, которые доступны только для чтения. Т.е. вы сможете только получить значения этих свойств, но не сможете присвоить им другие значения. Например, свойство Range(«A1»).Address которое содержит адрес ячейки. При попытке записать новое значение в такое свойство будет возникать ошибка.
Или же свойство Worksheets.Count — вы можете только получить количество листов, но не можете изменить количество листов, задав новое свойство Count. Для этого существуют методы объектов.

Методы объектов

В отличие от свойств, которые просто сохраняют или передают значение, методы выполняют какие-либо действия с объектом. Например метод Worksheets.Add создает новый пустой лист в книге. Еще один пример это метод Clear, который позволяет очистить содержимое ячеек. Следующий код очистит данные и форматы из диапазона ячеек A1:C10.

Есть аналогичная функция, которая не удаляет при этом форматирование ячеек, а только очищает их от значений

Методы могут иметь дополнительные аргументы. Например, метод AddComment имеет обязательный аргумент Text, в котором необходимо передать текст комментария к ячейке.

Также можно использовать следующий код для вызова методов. Возможно это более привычная запись, когда по аналогией с функцией Excel мы в скобках передаем аргументы этой функции.

Приемы и лайфхаки

Автоматическое заполнение кода по начальным символам

Часто, особенно на первых порах, вы не запомните точное название всех объектов, но будете помнить их первые символы. В редакторе кода вы можете использовать отобразить список названий и автоматически записать объект по первым символам. Для этого используйте сочетание клавиш Ctrl+ J и увидите список из предложенных вариантов.

Просмотр свойств и методов у объекта

Когда вы будете писать свои программы, то редактор кода VBE будет подсказывать список свойств и методов у объекта. Чтобы отобразить этот список достаточно ввести объект, например, Worksheets и поставить точку, отобразится список свойств и методов. Выберите нужный с помощью мышки или же используйте стрелки. Вы также можете начать писать название свойства и редактор кода подберет подходящее. Когда выбор сделан — нажимайте клавишу Tab.

Явно указывайте тип переменных

Предыдущий лайфхак не будет работать для созданных локальных переменных до тех пор, пока вы явно не укажите их тип. Например, если вы захотели создать переменную MySheet в которой хотите хранить текущий лист. То список свойств и методов у такой переменной вы не увидите. Но стоит добавить строчку кода и явно указать тип переменной:

И подсказки снова заработают.

Быстрый просмотр справки

Все свойства и методы знать невозможно, так как их тысячи. Первое время вы будете активно пользоваться справкой. Советую использовать официальную справку на сайте Microsoft.

Чтобы быстро посмотреть информацию по интересующему вас объекту, свойству или методу просто поставьте курсор на интересующий элемент кода и нажмите клавишу F1. В окне браузера откроется официальная справка по этому элементу.

Поиск по объектной модели

Также вначале пути у вас постоянно будут возникать вопрос «А как называется свойство, которое отвечает за. «. Иногда мы и не заем есть ли такое свойство/метод вообще. Хороший вариант изучения — просмотр объектной модели. Переходите в редактор кода VBA и нажимайте клавишу F2. Откроется окно с поиском по объектной модели. Тут вы найдете все имеющиеся свойства, методы, события и прочие элементы в модели. Просматривайте их, как правило в названии элемента заложена его суть и вы найдете то что искали. А в процессе поиска будете запоминать и другие элементы, которые будут попадаться на глаза.

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

  1. Открываем объектную модель клавишей F2.
  2. Так как мы хотим защитить лист, то логично предположить, что это метод в объекте Worksheet. Введем его в строку поиска и нажмем бинокль.
  3. В результатах поиска выбираем наш объект Worksheet и просматриваем его элементы.
  4. Находим метод Protect (Защита).
  5. Мы также можем просмотреть описание всех аргументов этого метода
  6. Конечно если что-то не понятно, то жмем клавишу F1 и открываем справку по этому методу с подробным описанием каждого аргумента.

На этом данную статью завершим, а в следующих мы более подробно поговорим про самый распространенный объект Excel — объект Range.

Источник

  • Remove From My Forums
  • Question

  • Hi,

    I’ve created an VSTO Excel Addin (C#). While the addin is activated in excel, I cannot use embedded Excel spreasheet objects in Word and getting the following error:

    The program used to create this object is Excel. That program is either not installed on your computer or it is not responding.

    To edit this object, install Excel or ensure that any dialog boxes in Excel are closed.

    How can I change my Excel Addin to get that working? 
    It isn’t a workaround for me to disable the Excel addin (then it works, of course), so I want to permanently use the Addin in Excel, but also work with embedded excel objects in word (without using the addin).

    How to get rid of that error? What can I do as developer? Is it necessary to determine on init if Excel is used stand alone or embedded?

    Best Regards

    Andreas

Answers

  • Hi Starain,

    its the latest of Office 2013 32-bit, all updates installed.

    I’ve found out that the problem is caused by attaching to the WorkbookOpen event in the Addin_Startup:

    Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);

    Releasing the Workbook COM Object solves the issue for me:

            void Application_WorkbookOpen(Excel.Workbook Wb)
            {
                try
                {
                    UpdateMenu();
                }
                catch(Exception e) {
                    logWriter.WriteLog(appConfig, «KxAddIn_Startup: Menu cannot be updated. » + e.ToString());
                }
                finally
                {
                    Marshal.ReleaseComObject(Wb);
                }
            }

    1.) Can you reproduce the issue when you attach to the WorkbookOpen event without calling ReleaseComObject?
    2.) Is this an acceptable and secure solution to call Marshal.ReleaseComObject(Wb) in the WorkbookOpen event handler?

    Best Regards

    Andreas

    • Proposed as answer by

      Friday, July 10, 2015 6:51 AM

    • Marked as answer by
      L.Hl
      Friday, July 10, 2015 9:15 AM

I use some objects like workbook, worksheet, app for Excel tasks. After I am done with Excel, I try releasing them by the code below. After all, I still see EXCEL.EXE at Task Manager. Why doesn’t it release completely?

My class for Excel tasks:

Excel._Application app = new Excel.Application();
Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
app.Visible = true;

worksheet.Cells[1, 1] = "test string";

workbook.SaveAs("C:testfile.xlsx");

object misValue = System.Reflection.Missing.Value;
workbook.Close(true, misValue, misValue);
app.Quit();

releaseObject(worksheet2);
releaseObject(workbook);
releaseObject(app);

releaseObject class:

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    } 

EXCEL.EXE is still at Task Manager:
enter image description here

asked Aug 5, 2012 at 22:54

Ned's user avatar

5

Already answered see:

How do I properly clean up Excel interop objects?

Basically COM objects are unmanaged objects (duh) and are not released when they go out of scope.
System.Runtime.InteropServices.Marshal.ReleaseComObject() can be used to release them before they get finalized (in the garbage collector), but you have to make sure to keep a reference of all the objects:
excelApp.Worksheets.Open() creates two objects: the collection ‘Worksheets’ and the ‘Worksheet’ opened with the Open() method.

Community's user avatar

answered Aug 6, 2012 at 1:47

Eli Algranti's user avatar

Eli AlgrantiEli Algranti

8,5792 gold badges42 silver badges50 bronze badges

It’s very easy to kill the EXCEL object from the Task Manager using Process, see below & enjoy..

//Kill the all EXCEL obj from the Task Manager(Process)
System.Diagnostics.Process[] objProcess = System.Diagnostics.Process.GetProcessesByName("EXCEL");

if (objProcess.Length > 0)
{
    System.Collections.Hashtable objHashtable = new System.Collections.Hashtable();

    // check to kill the right process
    foreach (System.Diagnostics.Process processInExcel in objProcess)
    {
        if (objHashtable.ContainsKey(processInExcel.Id) == false)
        {
             processInExcel.Kill();
        }
    }
    objProcess = null;
}

//In case of you want to quit what you have created the Excel object from your application //just use below condition in above,

    if(processInExcel.MainWindowTitle.ToString()== "")

answered Oct 26, 2012 at 10:37

Sambasivam Pathmaraj Mani's user avatar

It’s been a while since I’ve done Office Interop (I actually was using it for Outlook, but the concepts should be the same). The only way I was able to completely release everything was to do this:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Give it a shot….

answered Aug 5, 2012 at 23:45

BFree's user avatar

BFreeBFree

102k21 gold badges158 silver badges200 bronze badges

2

this is a problem that i could not solve. ive seen all of these answers before and i’ve implemented all of them, and still excel did not close. i had to do things with brute force. what i did was created a BAT file and ran it from my program. here are the contents of the file:

Taskkill /F /IM excel.exe

this will call ALL of your excels running. i would use this if you cannot figure out a different solution.

answered Aug 6, 2012 at 1:58

Alex Gordon's user avatar

Alex GordonAlex Gordon

55.8k284 gold badges666 silver badges1051 bronze badges

You need to close the excel application by doing like this as it opens excel program in background….

app .Application.Quit();

Add the above line code in your code in following way:

    object misValue = System.Reflection.Missing.Value;
    workbook.Close(true, misValue, misValue);
    app .Application.Quit();
    app.Quit();

answered Aug 5, 2012 at 23:07

Akash KC's user avatar

Akash KCAkash KC

15.9k6 gold badges39 silver badges59 bronze badges

1

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

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

A Quick Guide to VBA Objects

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

    Dim coll As New Collection
    Set GetCollection = coll

End Function

Receive from Function Dim coll As Collection
Set coll = GetCollection

The Webinar

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

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

vba objects video

Introduction

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

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

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

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

What is a VBA Object?

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

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

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

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

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

Dim Marks As Long

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

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

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

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

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

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

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

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

 
VBA Objects

Why VBA Uses Objects

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

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

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

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

A Real World Analogy

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

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

VBA Object Car

A nice looking combustion engine | © BigStockPhoto.com

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

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

Object Components

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

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

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

VBA Objects

 
What these icons mean is as follows

VBA Object Icons

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

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

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

' Prints the worksheet name
Debug.Print Sheet1.Name

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

Object Properties

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

' Set the name 
sheet1.Name = "Accounts"

' Get the name
sName = sheet1.Name

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

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

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

 
The workbook property Fullname is also a read-only property

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

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

Set rg = Sheet1.UsedRange

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

Object Methods

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

' Collection Add method
Coll.Add "Apple"

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

Another example of a method is the Workbook SaveAs method

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

 
and the Worksheets Protect and Copy methods

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

Object Events

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

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

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

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

Creating a VBA Object

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

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

Dim coll As Collection

coll.Add "Apple"

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

VBA Object nothing

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

VBA Object Variable

 
There are three steps to creating a VBA object

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

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

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

Using Dim with New

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

' Declare, Create and Assign
Dim coll As New Collection

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

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

Using Set with New

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

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

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

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

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

Dim coll As Collection

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

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

Subtle Differences of Dim Versus Set

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

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

Dim coll As New Collection

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

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

Object variable or With block variable not set

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

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

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

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

Dim coll As Collection

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

coll.Add "Pear"

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

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

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

When New Is Not Required

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

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

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

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

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

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

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

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

Dim wk3 As Workbook
Set wk3 = wk2

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

Using CreateObject

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

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

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

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

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

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

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

Assigning VBA Objects

We can assign basic variables using the Let keyword.

Dim sText As String, lValue As Long

Let sText = "Hello World"
Let lValue = 7

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

sText = "Hello World"
lValue = 7

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

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

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

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

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

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

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

coll2 = coll1

 
VBA Set

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

  • Let stores a value
  • Set stores an address

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

VBA Objects in Memory

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

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

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

Dim X As long, Y As Long

 
VBA Set Memory

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

X = 25
Y = 12

 
VBA Basic Memory

 
We saw the following line of code earlier in this post

Dim coll As New Collection
 

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

stores the address of the object

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

VBA Objects in Memory

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

How Set Works

Take a look at the following code

Dim coll1 As New Collection
Dim coll2 As Collection

Set coll2 = coll1

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

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

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

 
VBA Objects in Memory

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

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

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

Dim wk3 As Workbook
Set wk3 = Workbooks(2)

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

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

VBA Workbook Object

If we use code like the following

wk1.SaveAs "C:TempNewName.xlsx"

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

To sum up what we have learned in this section:

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

Objects and Procedures

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

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

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

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

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

End Sub

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

Using ByRef and ByVal

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Sub

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

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

Why VBA Uses Pointers

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

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

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

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

VBA Object - Library

© BigStockPhoto.com

Running a Simple Memory Experiment

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

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

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

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

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

End Sub

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

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

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

 
you will notice

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

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

Cleaning Up Memory

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

Dim coll As Collection

Set coll = New Collection
coll.Add "Apple"

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

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

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

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

Clean Up Example

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

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

Public Firstname As String

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

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

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

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

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

Setting Objects to Nothing

In code examples you may see code like

Set coll = Nothing

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

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

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

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

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

Memory Summary

To sum up what we have learned in this section:

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

Why Set Is Useful

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

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

Public Firstname As String
Public Surname As String

Set Example 1

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

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

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

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

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

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

End Sub

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

Set Example 2

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

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

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

End Sub

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

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

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

What’s Next?

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

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

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

Like this post? Please share to your friends:
  • This month excel vba
  • This letter is silent in the word
  • This is your last word
  • This is your dance word
  • This is word of god