我需要从Excel编写正确的"参考"MS Outlook

M. *_*. H 3 excel vba excel-vba outlook-vba

我想运行一些代码Excel,与之对话Outlook.在我的机器上,我可以从Tools->ReferencesVBE中选择正确的参考.

但我希望我的代码也可以在他们的机器上为其他用户运行,他们都有不同版本的Outlook和Excel,

有没有一种整洁的方法我可以让代码选择正确的MS Outlook引用,或告诉我是否没有安装Outlook等?

谢谢

Dav*_*ens 7

我使用这样的函数应该适用于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
Run Code Online (Sandbox Code Playgroud)

此函数检查引用是否存在(或不存在)

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
Run Code Online (Sandbox Code Playgroud)

另外

使用早期绑定(与基准)制定你的机器上的代码,然后分发之前,所有的具体前景申述(例如,改变As MailItem,As Outlook.Application等等),以通用As Object型.您的代码仍将执行,不需要引用.

通过后期绑定,所需的只是适当的库位于用户的计算机上.这通常不是问题,因为您没有使用任何类型的自定义类型库或DLL,而是一个标准的Office组件库,它不属于正常的Windows安装.

立即想到的唯一其他区别是您不能New在分配或声明时使用关键字,例如:

Dim olApp as New Outlook.Application
Run Code Online (Sandbox Code Playgroud)

要么:

Dim olApp as Outlook.Application
Set olApp = New Outlook.Application
Run Code Online (Sandbox Code Playgroud)

相反,您必须使用以下CreateObject方法:

Dim olApp as Object 'Outlook.Application object
Set olApp = CreateObject("Outlook.Application")
Run Code Online (Sandbox Code Playgroud)