Как создать объект в vba excel

Создание объекта Collection с помощью кода VBA Excel. Методы коллекции и синтаксис выражений с ними. Свойство Count и примеры кода.

Collection – это объект, представляющий из себя упорядоченный набор данных (коллекцию), на который можно ссылаться как на одно целое. Элементы коллекции никак между собой не связаны и могут иметь разные типы данных.

Создать новый экземпляр Collection в коде VBA Excel можно двумя строками:

Dim myColl As Object

Set myColl = New Collection

или одной строкой:

Dim myColl As New Collection

Лист автоматической вставки объектов, методов и свойств (лист подсказок) предоставит при написании кода VBA Excel простой доступ к методам Add, Item, Remove и свойству Count объекта Collection:

Лист подсказок отображается автоматически после ввода точки или, в иных случаях, вызывается сочетанием клавиш «Ctrl+Пробел».

Методы и свойство коллекции

Метод Add

Метод Add добавляет новый элемент в объект Collection.

Синтаксис метода Add:

Collection.Add Элемент, [Ключ], [До], [После]

Компоненты метода Add:

  1. Collection – обязательный компонент, представляющий выражение (переменную), возвращающее объект Collection.
  2. Элемент (item) – обязательный аргумент, представляющий выражение любого типа, возвращающее элемент, который необходимо добавить в коллекцию.
  3. Ключ (key) – необязательный аргумент, представляющий строковое выражение, задающее уникальный ключ, который может использоваться вместо индекса позиции для доступа к элементу коллекции.
  4. До* (before) – необязательный аргумент, указывающий на позицию существующего элемента в коллекции, перед которым будет добавлен новый элемент.
  5. После* (after) – необязательный аргумент, указывающий на позицию существующего элемента в коллекции, после которого будет добавлен новый элемент.

* Аргументы «До» и «После» не могут применяться одновременно. Если аргументу «До» или «После» присвоено числовое значение, оно должно быть в пределах диапазона от 1 до значения свойства Collection.Count. Если это строка, она должна соответствовать одному из ключей существующих в коллекции элементов.

Метод Item

Метод Item возвращает элемент объекта Collection по индексу позиции или по ключу.

Синтаксис метода Item объекта Collection:

Компоненты метода Item:

  • Collection – обязательный компонент, представляющий выражение (переменную), возвращающее объект Collection.
  • Index – обязательный аргумент, представляющий выражение, возвращающее номер (индекс) позиции элемента коллекции или его уникальный ключ.

Метод Remove

Метод Remove удаляет элемент из объекта Collection по индексу позиции или по ключу.

Синтаксис метода Remove объекта Collection:

Collection.Remove (Index)

Компоненты метода Remove:

  • Collection – обязательный компонент, представляющий выражение (переменную), возвращающее объект Collection.
  • Index – обязательный аргумент, представляющий выражение, возвращающее номер (индекс) позиции элемента коллекции или его уникальный ключ.

Свойство Collection.Count

Свойство Count объекта Collection возвращает количество элементов в коллекции.

Примеры кода с объектом Collection

Пример 1
Создание нового экземпляра объекта Collection, добавление в коллекцию трех элементов, определение количества элементов в коллекции, извлечение одного и того же элемента по индексу и по ключу:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Primer1()

‘Создаем новый экземпляр

‘объекта Collection

Dim myColl As New Collection

‘Добавляем три элемента

myColl.Add «Первый элемент»

myColl.Add «Второй элемент», «Ключ 2»

myColl.Add «Третий элемент»

‘Определение количества элементов

MsgBox myColl.Count

‘Извлечение одного и того же элемента

‘коллекции по индексу и по ключу

MsgBox myColl.Item(2) & _

» (извлечен по индексу)»

MsgBox myColl.Item(«Ключ 2») & _

» (извлечен по ключу)»

End Sub

Пример 2
Добавление элементов в коллекцию с использованием аргументов «До» и «После»:

Sub Primer2()

Dim myColl As New Collection

‘Добавляем три первых элемента

myColl.Add «Второй элемент»

myColl.Add «Третий элемент»

myColl.Add «Пятый элемент»

‘Следующий элемент вставляем перед первым

myColl.Add «Первый элемент», , 1

‘Следующий элемент вставляем после третьего

‘с учетом добавленного предыдущей строкой

myColl.Add «Четвертый элемент», , , 3

‘Извлекаем первый и четвертый элементы

MsgBox myColl.Item(1)

MsgBox myColl.Item(4)

End Sub

Пример 3
Генерация ошибки при добавлении в коллекцию нового элемента с неуникальным ключом:

Sub Primer3()

Dim myColl As New Collection

On Error GoTo Instr

myColl.Add «Первый элемент», «Ключ»

myColl.Add «Второй элемент», «Ключ»

Exit Sub

Instr:

MsgBox «Произошла ошибка: « & Err.Description

End Sub

Эта особенность объекта Collection используется для отбора уникальных значений из списка элементов.

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!

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]

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

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA CreateObject (wallstreetmojo.com)

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

Понравилась статья? Поделить с друзьями:
  • Как создать объект wordart в word
  • Как создать общую формулу в excel
  • Как создать общую таблицу excel
  • Как создать общий доступ к файлу excel
  • Как создать общий документ word