当从 Visual Basic 中将一个引用添加到项目中时,ItemAdded 事件发生。
? | ItemAdded 事件可应用于 References 集合。与大多数其他事件不同的是,该事件与控件、窗体或报表无关。因此,要创建 ItemAdded 事件过程的过程定义,必须使用特殊的语法。 |
? | ItemAdded 事件只能在事件本身发生时才运行事件过程,该事件不能运行宏。 |
ItemAdded 事件只有从代码添加引用时才会发生。执行以下操作添加引用时,该事件不会发生:当“模块”窗口为活动窗口时,单击“工具”菜单中的“引用”,显示“引用”对话框后,在“引用”对话框中添加引用。
以下示例包含 ItemAdded 与 ItemRemoved 事件的事件过程。若要试用该示例,请先新建一个类模块,方法是:单击“插入”菜单中的“类模块”,然后将下列代码粘贴到类模块中,并将模块保存为 RefEvents:
' Declare object variable to represent References collection.
Public WithEvents evtReferences As References
' When instance of class is created, initialize evtReferences
' variable.
Private Sub Class_Initialize()
Set evtReferences = Application.References
End Sub
' When instance is removed, set evtReferences to Nothing.
Private Sub Class_Terminate()
Set evtReferences = Nothing
End Sub
' Display message when reference is added.
Private Sub evtReferences_ItemAdded(ByVal Reference As _
Access.Reference)
MsgBox "Reference to " & Reference.Name & " added."
End Sub
' Display message when reference is removed.
Private Sub evtReferences_ItemRemoved(ByVal Reference As _
Access.Reference)
MsgBox "Reference to " & Reference.Name & " removed."
End Sub
以下的 Function 过程可用来添加一个特定的引用。在添加引用时,将执行 RefEvents 类中定义的 ItemAdded 事件过程。
例如,若要将引用设为日历控件,可以传递“C:\Windows\System\Mscal.ocx”字符串(只要该字符串是日历控件在计算机上的正确位置)。
' Create new instance of RefEvents class.
Dim objRefEvents As New RefEvents
' Pass file name and path of type library to this procedure.
Function AddReference(strFileName As String) As Boolean
Dim ref As Reference
On Error GoTo Error_AddReference
' Create new reference on References object variable.
Set ref = objRefEvents.evtReferences.AddFromFile(strFileName)
AddReference = True
Exit_AddReference:
Exit Function
Error_AddReference:
MsgBox Err & ": " & Err.Description
AddReference = False
Resume Exit_AddReference
End Function