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]
How do I create an excel file using VBScript
? I searched the net but it just mentions opening an existing file.
This is the extraction from the Internet shown below
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:ScriptsNew_users.xls")
I want to know how do you create a new excel file or .xls
using vbscript
?
Thanks and regards
Maddy
ckpepper02
3,2675 gold badges29 silver badges43 bronze badges
asked Jul 14, 2009 at 5:36
2
Here is a sample code
strFileName = "c:test.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)
objExcel.Quit
answered Jul 14, 2009 at 5:52
ShobanShoban
22.9k8 gold badges63 silver badges107 bronze badges
1
set objExcel = CreateObject("Excel.Application")
objExcel.Application.DisplayAlerts = False
set objWorkbook=objExcel.workbooks.add()
objExcel.cells(1,1).value = "Test value"
objExcel.cells(1,2).value = "Test data"
objWorkbook.Saveas "c:testXLS.xls"
objWorkbook.Close
objExcel.workbooks.close
objExcel.quit
set objExcel = nothing `
CJ7
22.3k65 gold badges186 silver badges318 bronze badges
answered Mar 23, 2015 at 11:48
MD5MD5
1,31615 silver badges14 bronze badges
'Create Excel
Set objExcel = Wscript.CreateObject("Excel.Application")
objExcel.visible = True
Set objWb = objExcel.Workbooks.Add
objWb.Saveas("D:Example.xlsx")
objExcel.Quit
answered May 17, 2016 at 7:26
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = true
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)
intRow = 2
dim ch
objWorksheet.Cells(1,1) = "Name"
objWorksheet.Cells(1,2) = "Subject1"
objWorksheet.Cells(1,3) = "Subject2"
objWorksheet.Cells(1,4) = "Total"
for intRow = 2 to 10000
name= InputBox("Enter your name")
sb1 = cint(InputBox("Enter your Marks in Subject 1"))
sb2 = cint(InputBox("Enter your Marks in Subject 2"))
total= sb1+sb2+sb3+sb4
objExcel.Cells(intRow, 1).Value = name
objExcel.Cells(intRow, 2).Value = sb1
objExcel.Cells(intRow, 3).Value = sb2
objExcel.Cells(intRow, 4).Value = total
ch = InputBox("Do you want continue..? if no then type no or y to continue")
If ch = "no" Then Exit For
Next
objExcel.Cells.EntireColumn.AutoFit
MsgBox "Done"
enter code here
answered Jan 14, 2015 at 5:21
PiushPiush
212 bronze badges
This code creates the file temp.xls in the desktop but it uses the SpecialFolders property, which is very useful sometimes!
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strDesktop & "temp.xls")
answered Sep 15, 2015 at 13:37
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
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: –
- 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
Declare the variable as PowerPoint.Application.
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
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
Now, open the CreateObject function.
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
Now, the CreateObject function will initiate the PowerPoint application. Once we initiate the object, we need to make it visible using the variable name.
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
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.
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
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.
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
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
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
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
It is used to Perform Operations on Excel Application.
Excel Application
Excel File / Excel Workbook
Excel Sheet / Excel Worksheet
Create Excel Application Object
Syntax:
Set variable = CreateObject(“Class value”)
example
Set objExcel = CreateObject(“Excel.Application”)
VBScript Excel Scripting Examples:
1) Create an Excel file
Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True ‘To view the Operation during execution
objExcel.Workbooks.Add ‘To create new file
objExcel.ActiveWorkbook.SaveAs “C:UsersG C REDDYDesktopJanuary.xlsx”
objExcel.Quit ‘To close the Excel Application
Set objExcel = Nothing
2) Check the existence of January file, If not exists then create the file.
Dim objFso, objExcel
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)
If Not objFso.FileExists(“C:UsersG C REDDYDesktopJanuary.xlsx”) Then
objExcel.Workbooks.Add ‘To create new file
objExcel.ActiveWorkbook.SaveAs “C:UsersG C REDDYDesktopJanuary.xlsx”
End If
objExcel.Quit
Set objExcel = Nothing
3) Check the existence of January file, If exists then open the file and enter some data. if not exists then create the file and enter some data.
Dim objFso, objExcel, FilePath
FilePath = “C:UsersG C REDDYDesktopJanuary.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)
If objFso.FileExists(FilePath) Then
objExcel.Workbooks.Open(FilePath)
objExcel.Worksheets(1).Cells(1,1) = “Hello UFT”
objExcel.ActiveWorkbook.Save
Else
objExcel.Workbooks.Add
objExcel.Worksheets(1).Cells(1,1) = “Hello UFT”
objExcel.ActiveWorkbook.SaveAs(FilePath)
End If
objExcel.Quit
Set objExcel = Nothing
Excel objects
1) Excel Application Object
It is Used to perform operations on Excel Application
Set variable = CreateObject(“Excel.Application”)
2) Excel Workbook Object
It is used to work with Excel files/Workbooks
Set variable = ExcelApplicationObject.Workbooks.Add/Open(“File Path”)
3) Excel Worksheet Object
It is used to work with Excel Sheets/Worksheets
Set variable = ExcelWorkbookObject.Worksheets(Sheet Id Or “Sheet Name”)
Excel Application Object is always only one
We can create one or more Excel Workbook objects
We can create one or more Excel Worksheet objects for every workbook object
Difference between FileSystemObject model and Excel object model in case of Sub Objects.
> In FileSystemObject model creating Text stream object (sub object) is mandatory to perform Text(Read, write etc…) related operations
> In Excel object model creating sub objects is optional, but if you want work with multiple files and multiple sheets then sub objects are required.
4) Check the existence of January file, If exists then open the file and enter some data. if not exists then create the file and enter some data.(Using Sub and Sub-sub objects)
Dim objFso, objExcel, FilePath, objWorkbook, objWorksheet
FilePath = “C:UsersG C REDDYDesktopJanuary.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)
If objFso.FileExists(FilePath) Then
Set objWorkbook = objExcel.Workbooks.Open(FilePath)
Set objworksheet = objWorkbook.Worksheets(1)
objWorksheet.cells(1, 1) =”Hello UFT”
objWorkbook.Save
Else
Set objWorkbook = objExcel.Workbooks.Add
Set objworksheet = objWorkbook.Worksheets(1)
objWorksheet.cells(1, 1) =”Hello UFT”
objWorkbook.SaveAs(FilePath)
End If
objExcel.Quit
Set objWorksheet = Nothing
Set objworkbook = Nothing
Set objExcel = Nothing
5) Read Test data from an Excel file and perform Data driven testing for Login Functionality
Dim objExcel, objWorkbook, objWorksheet, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:UsersG C REDDYDesktopJanuary.xlsx”)
Set objWorksheet = objWorkbook.Worksheets(1)
RowsCount = objWorksheet.usedRange.Rows.Count
For i = 2 To RowsCount Step 1
SystemUtil.Run “C:Program FilesHPUnified Functional Testingsamplesflightappflight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set objWorksheet.Cells(i, “A”) ‘i for Row, A for Column
Dialog(“Login”).WinEdit(“Password:”).Set objWorksheet.Cells(i, 2)’i for Row, 2 for Column
Wait 2
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).Close
Next
objExcel.Quit
Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
Follow me on social media:
Раннее и позднее связывание переменных с экземплярами внешних и внутренних объектов в VBA Excel. Преимущества ранней привязки объектов. Примеры кода.
Связывание – это процесс назначения внутреннего или внешнего объекта переменной.
Внутренними называются объекты, которые принадлежат объектной модели Excel (Range, Sheet, Workbook, Chart). Внешние объекты не принадлежат объектной модели Excel. А также новый экземпляр Excel.Application является внешним объектом по отношению к тому экземпляру приложения Excel, из которого он создается.
Раннее связывание
Раннее связывание – это объявление переменной с определенным типом объекта или присвоение переменной, при ее объявлении, нового экземпляра внешнего объекта.
Определение типа объекта при ранней привязке выполняется еще до запуска приложения.
Объявление переменной определенного типа
Объявление переменной с определенным типом объекта:
‘Внутренние объекты Dim myRange As Range Dim mySheet As Sheets Dim myWorkbook As Workbook ‘Внешние объекты Dim myDictionary As Dictionary Dim myExcel As Excel.Application Dim myWord As Word.Application |
При объявлении переменной с определенным типом объекта ранняя привязка уже осуществилась, но чтобы начать работу с переменной, ей необходимо присвоить конкретный (для внутренних объектов) или новый (для внешних объектов) экземпляр объекта с помощью ключевого слова Set:
‘Внутренние объекты Set myRange = Range(«A1:D10») Set mySheet = Sheets(1) Set myWorkbook = Workbooks.Open(«C:Книга1.xlsm») ‘Внешние объекты Set myDictionary = New Dictionary Set myExcel = New Excel.Application Set myWord = New Word.Application |
Присвоение переменной объекта при объявлении
Присвоение переменной, при ее объявлении, нового экземпляра внешнего объекта:
Dim myDictionary As New Dictionary Dim myExcel As New Excel.Application Dim myWord As New Word.Application |
Ссылка на библиотеку внешнего объекта
Чтобы использовать раннее связывание для внешнего объекта, необходимо подключить в редакторе VBA Excel ссылку на библиотеку этого объекта, если она еще не подключена. Подключается ссылка на библиотеку в окне «References VBAproject», перейти в которое можно через главное меню редактора: Tools–>References…
Ссылка на библиотеку Microsoft Scripting Runtime, которая необходима для ранней привязки объекта Dictionary:
Ссылка на библиотеку Microsoft Word Object Library, которая необходима для ранней привязки объекта Word.Application:
После выбора библиотеки следует нажать кнопку «OK».
Преимущества ранней привязки
Главное преимущество раннего связывания заключается в возможности использовать при написании кода VBA Excel лист выбора и вставки свойств-методов привязанных объектов (Auto List Members). Лист подсказок отображается автоматически или вызывается сочетанием клавиш «Ctrl+Пробел» или «Ctrl+J».
Кроме того, применение ранней привязки для создания объекта с помощью ссылки на библиотеку объектов обеспечивает более высокую производительность приложения.
В том, что раннее и позднее связывание работает не только с внешними, но и с внутренними объектами, вы можете убедиться на следующих примерах.
Скопируйте процедуру Primer1 с ранней привязкой объекта Sheet в любой программный модуль:
Sub Primer1() Dim mySheet As Sheet mySheet End Sub |
Поставьте точку после mySheet в 3 строке и вы увидите лист выбора и вставки свойств-методов:
Если вдруг лист подсказок не отобразился автоматически, его можно вызвать сочетанием клавиш «Ctrl+Пробел» или «Ctrl+J».
Теперь скопируйте процедуру Primer2 с поздней привязкой объекта Sheet в любой программный модуль:
Sub Primer2() Dim mySheet As Object Set mySheet = Sheets(1) mySheet End Sub |
Поставьте точку после mySheet в 4 строке – лист подсказок не отобразится:
Сочетания клавиш «Ctrl+Пробел» и «Ctrl+J» тоже не помогут. В данном случае тип объекта, присвоенного переменной, определяется только в процессе выполнения программы.
Позднее связывание
Позднее связывание – это присвоение переменной, объявленной как Object, экземпляра внутреннего объекта с помощью ключевого слова Set или экземпляра внешнего объекта с помощью ключевого слова Set и функции GetObject или CreateObject.
Тип объекта при поздней привязке определяется только в процессе выполнения программы.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
‘Внутренние объекты ‘Диапазон ячеек Dim myRange As Object Set myRange = Range(«A1:D10») ‘Рабочий лист Dim mySheet As Object Set mySheet = Sheets(1) ‘Рабочая книга Excel Dim myWorkbook As Object Set myWorkbook = Workbooks.Open(«C:Книга1.xlsm») ‘Внешние объекты ‘Словарь Dim myDictionary As Object Set myDictionary = CreateObject(«Scripting.Dictionary») ‘Приложение Excel Dim myExcel As Object Set myExcel = CreateObject(«Excel.Application») ‘Приложение Word Dim myWord As Object Set myWord = CreateObject(«Word.Application») |
Функция CreateObject используется для создания нового экземпляра объекта, а функция GetObject – для получения сохраненного объекта.
Если проект создается на заказ, следует применять позднее связывание, так как на компьютере пользователя может не оказаться нужной библиотеки. При написании кода используйте раннюю привязку, а когда все будет готово, замените ее на позднюю.