2023年11月30日发(作者:)
CreateObject函数
Office 2013 and later
创建并返回对 ActiveX 对象的引⽤。
语法
CreateObject( class,[servername] )
CreateObject 函数语法包含以下部分:
部分说明
class必需;Variant (String)。要创建对象的应⽤程序名称和类。
servername
可选;Variant (String)。将在其中创建对象的⽹络服务器的名称。如果
servername 为空字符串 (""),则使⽤本地计算机。
class 参数 使⽤ appname.objecttype 语法并包含以下部分:
部分说明
appname必需;Variant (String)。提供对象的应⽤程序的名称。
objecttype必需;Variant (String)。要创建对象的类型或类。
备注
每个⽀持 Automation 的应⽤程序都提供⾄少⼀种类型的对象。例如,字处理应⽤程序可能
提供 Application 对象、Document 对象和 Toolbar 对象。
要创建 ActiveX 对象,请将 CreateObject 返回的对象指定给对象变量:
VBA
复制
' Declare an object variable to hold the object
' reference. Dim as Object causes late binding.
Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("")
此代码使应⽤程序开始创建对象,本⽰例中为 Microsoft Excel 电⼦表格。创建对象后,可
以使⽤定义的对象变量在代码中进⾏引⽤。在下⾯的⽰例中,访问使⽤对象变量的新对象
的属性和⽅法 、ExcelSheet以及其他 Microsoft Excel 对象(包括 Application 对象与
Cells集合)。
VBA
复制
' Make Excel visible through the Application object.
e = True
' Place some text in the first cell of the sheet.
(1, 1).Value = "This is column A, row 1"
' Save the sheet to C: directory.
"C:"
' Close Excel with the Quit method on the Application object.
' Release the object variable.
Set ExcelSheet = Nothing
使⽤ As Object 字句声明对象变量将创建可包含对任意类型对象的引⽤的变量。但是,通
过该变量访问该对象属于晚期绑定(即,在程序运⾏时绑定)。要创建导致早期绑定
(即,在编译程序时绑定)的对象变量,请使⽤特定的类 ID 声明对象变量。例如,可以声
明并创建以下 Microsoft Excel 引⽤:
VBA
复制
Dim xlApp As ation
Dim xlBook As ok
Dim xlSheet As eet
Set xlApp = CreateObject("ation")
Set xlBook =
Set xlSheet = eets(1)
通过早期绑定变量进⾏引⽤可实现更佳的性能,但只能包含对声明中所指定类的引⽤。
可以将 CreateObject 函数返回的对象传递到预期对象为参数的函数。例如,使⽤以下代码
创建并传递对 ation 对象的引⽤:
VBA
复制
Call MySub (CreateObject("ation"))
可以通过将计算机的名称传递到CreateObject 的 servername 参数在远程⽹络计算机上创
建对象。该名称与共享名称的"计算机名称"部分相同:如果共享名称
为"MyServerPublic",则 servername 为"MyServer"。
注释
有关使应⽤程序在远程⽹络计算机上可见的其他信息,请参阅 COM ⽂档(请参见
Microsoft Developer Network)。可能需要对应⽤程序添加注册表项。
以下代码返回在名为 MyServer 的远程计算机上运⾏的 Excel 实例的版本号:
VBA
复制
Dim xlApp As Object
Set xlApp = CreateObject("ation", "MyServer")
n
如果远程服务器不存在或不可⽤,则出现运⾏时错误。
注释
如果没有对象的当前实例,请使⽤ CreateObject。如果对象实例已在运⾏,则启动新的
实例并创建指定类型的对象。要使⽤当前实例,或启动应⽤程序并加装⽂件,请使⽤
GetObject 函数。
如果对象本⾝注册为单实例对象,⽆论执⾏多少次 CreateObject 都只创建⼀个对象实例。
⽰例
本⽰例使⽤ CreateObject 函数来设置对 Microsoft Excel 的引⽤ (xlApp)。其通过引⽤访问
Microsoft Excel 的 Visible 属性,再使⽤ Microsoft Excel Quit ⽅法进⾏关闭。最后,释放
引⽤本⾝。
VBA
复制
Dim xlApp As Object ' Declare variable to hold the reference.
Set xlApp = CreateObject("ation")
' You may have to set Visible property to True
' if you want to see the application.
e = True
' Use xlApp to access Microsoft Excel's
' other objects.


发布评论