VBS教程:函数-CreateObject 函数


CreateObject 函数

创建并返回对 Automation 对象的引用 。

CreateObject(servername.typename [, location])

参数

servername

必选项 。提供对象的应用程序名称 。

typename

必选项 。要创建的对象类型或类 。

location

可选项 。对象所在的网络服务器将被创建 。

说明

Automation 服务器至少提供一种对象类型 。例如,字处理应用程序可以提供应用程序对象、文档对象和工具条对象 。

要创建 Automation 对象,将 CreateObject 函数返回的对象赋值给某对象变量:

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

上述代码启动创建对象(在此实例中,是 Microsoft Excel 电子表格)的应用程序 。对象创建后,就可以在代码中使用定义的对象变量引用此对象 。在下面的示例中,可使用对象变量、ExcelSheet 和其他 Excel 对象,包括 Application 对象和 Cells 集合访问新对象的属性和方法 。例如:

 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.ExcelSheet.Application.Quit Release the object variable.Set ExcelSheet = Nothing

在远程服务器上创建一个对象,当 Internet 安全关闭时只能完成 。通过传递计算机名到 CreateObject 服务器名的参数,能在远程网络上创建对象 。该名称如同共享部份的机器名 。例如网络共享名命名为: "\\myserver\public", servername 是 "myserver" 。另外,只能指定 servername 使用 DNS 格式或 IP 地址 。

以下代码返回运行在命名为"myserver"的远程网络计算机上 Excel 实例的版本号 :

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

错误发生在指定的远程服务器不存在或无法找到 。