VBS tutorial: function – CreateObject function


CreateObject function

Creates and returns a reference to an automation object.

CreateObject(servername.typename [, location])



Required. Provide the application name of the object.


Required. The object type or class to create.


Optional. The network server where the object is located will be created.


The automation server provides at least one object type. For example, a word processing application can provide application objects, document objects, and toolbar objects.

To create an automation object, assign the object returned by the CreateObject function to an object variable:

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

The above code starts the application that creates the object (in this example, a Microsoft Excel spreadsheet). Once an object is created, it can be referenced in code using defined object variables. In the following example, you can use object variables, excelsheets, and other excel objects, including the application object and the cells collection, to access the properties and methods of the new object. For example:

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

Creating an object on a remote server can only be done when Internet security is turned off. You can create an object on a remote network by passing the parameter from the computer name to the CreateObject server name. The name is like the machine name of the shared part. For example, the name of the network share is: \ \ Myserver \ public, and the servername is “Myserver”. In addition, only DNS format or IP address can be specified for servername.

The following code returns the version number of an excel instance running on a remote network computer named “Myserver”:

Function GetVersion
 Dim XLApp
 Set XLApp = CreateObject("Excel.Application", "MyServer")
 GetVersion = XLApp.Version
End Function

The error occurred when the specified remote server does not exist or cannot be found.