【问题标题】:How to select 'Reference' to user's version of MS Outlook from Excel?如何从 Excel 中选择“参考”到用户的 MS Outlook 版本?
【发布时间】:2014-08-29 02:28:56
【问题描述】:

我想在 Excel 中运行与 Outlook 对话的代码。

我可以从 VBE 的 Tools->References 中选择正确的引用。

我希望我的代码可以为其他用户运行。他们将拥有不同版本的 Outlook 和 Excel。

有没有办法让代码选择正确的 MS Outlook 引用,或者告诉我是否未安装 Outlook 等?

【问题讨论】:

标签: excel vba outlook


【解决方案1】:

我使用这样的函数,它应该适用于 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")

【讨论】:

  • 太棒了——非常全面。我将尝试后期绑定,我没有意识到这意味着我不需要参考。谢谢
  • 当然。试一试,我添加了一些细节,可能有助于您从早期绑定转换为后期绑定。
  • 您在哪里实现此功能以确保在需要之前添加引用?
  • @schizoid04 如果您有自己的问题,请提出一个新的和单独的问题,而不是在 4 年前的帖子中寻求答案 :)
  • 我已将其添加到此处,因为它与您发布的答案相关,并且要求对您的答案进行进一步澄清。
【解决方案2】:

第一个子的小附加:

 Sub AddRefToOutlook()

 'This subroutine adds the reference if it doesn't already exist
Const outlookRef As String = "C:\Program Files (x86)\Microsoft Office\Office14\MSOUTL.OLB"

If Not RefExists(outlookRef, "Microsoft Outlook " & CLng(Split(Application.Version, ".")(0)) & ".0 Object Library") Then
    Application.VBE.ActiveVBProject.References.AddFromFile ("MSOUTL.OLB")
End If
End Sub

【讨论】:

    猜你喜欢
    • 2011-02-16
    • 2023-03-31
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    相关资源
    最近更新 更多