我使用这样的函数,它应该适用于 Outlook 2010。如果您使用的是不同版本的 Office,您可能需要更改路径/参数,或者如果您必须处理多个版本的 Office,那么您将需要一些额外的逻辑来处理版本控制,但这是它的基础。
如果引用不存在,则此子例程添加引用
Sub AddRefToOutlook()
Const outlookRef as String = "C:\Program Files (x86)\Microsoft Office\Office14\MSOUTL.OLB"
If Not RefExists(outlookRef, "Microsoft Outlook 14.0 Object Library") Then
Application.VBE.ActiveVBProject.References.AddFromFile _
outlookRef
End If
End Sub
此函数检查引用是否存在(或不存在)
Function RefExists(refPath As String, refDescrip As String) As Boolean
'Returns true/false if a specified reference exists, based on LIKE comparison
' to reference.description.
Dim ref As Variant
Dim bExists As Boolean
'Assume the reference doesn't exist
bExists = False
For Each ref In Application.VBE.ActiveVBProject.References
If ref.Description Like refDescrip Then
RefExists = True
Exit Function
End If
Next
RefExists = bExists
End Function
或者
使用早期绑定(带有参考)在您的机器上开发代码,然后在分发之前,将所有特定于 Outlook 的声明(例如,As MailItem、As Outlook.Application 等)更改为通用 As Object类型。您的代码仍将执行,并且不需要引用。
使用后期绑定只需要在用户的机器上安装适当的库即可。这通常不是问题,因为您使用的不是任何类型的自定义类型库或 dll,而是一个标准的 Office 组件库,它不会成为正常 Windows 安装的一部分。
立即想到的另一个区别是您不能在赋值或声明中使用New 关键字,例如:
Dim olApp as New Outlook.Application
或者:
Dim olApp as Outlook.Application
Set olApp = New Outlook.Application
相反,您必须使用CreateObject 方法:
Dim olApp as Object 'Outlook.Application object
Set olApp = CreateObject("Outlook.Application")