从Excel创建Outlook约会(Office 2013和Office 2016)

时间:2019-05-07 13:04:49

标签: excel vba outlook

我有用于从Excel创建Outlook约会的代码。

问题是……

  • Office 2013使用 Microsoft Word 15.0 对象库
  • Office 2016/365使用 Microsoft Word 16.0 对象库

然后,出现有关Office 2013版本中缺少参考的错误。

有什么方法可以使其同时在Office 2013和Office 2016版本中工作?

这是我的代码:

Sub CreateNewOutlookAppointment()     
    Dim olApp As Outlook.Application
    Dim olAppt As Outlook.AppointmentItem
    Dim myInspector As Outlook.Inspector

    Set olAppt = Nothing
    Set olApp = Outlook.Application
    Set olAppt = olApp.CreateItem(olAppointmentItem)

    Set myInspector = olAppt.GetInspector 
    myInspector.Activate

    With olAppt
        .Subject = "Review" & ", " & ThisWorkbook.Sheets("Other Data").Range("P23").Value
        ThisWorkbook.Sheets("Templates").Range("M202:M223").Copy
        .Display
        .GetInspector.WordEditor.Windows(1).Selection.PasteAndFormat wdPASTERTF

        .Attachments.Add Environ("temp") & "\" & _
        ThisWorkbook.Sheets("Other Data").Range("AK2").Value & ", " & _
        "Bid review" & ".pdf"  
    End With

    Application.SendKeys ("%HOM")  
End Sub

1 个答案:

答案 0 :(得分:1)

使用后期绑定代替早期绑定,并完全删除对Outlook库的引用。参见Using early binding and late binding in Automation

请注意,在后期绑定中,您不再具有Intelli Sense工具提示。而且您不能使用任何Outlook枚举。


这对您的代码意味着什么?

因此将Outlook变量声明为Object,然后使用后期bindinding创建Outlook应用程序:Set olApp = CreateObject("Outlook.Application")

请注意,您将无法再使用olAppointmentItem之类的Outlook枚举。相反,您需要使用它们的实际值(在olAppointmentItem的情况下为1

Set olAppt = olApp.CreateItem(1)

或者您需要将它们定义为常量以使用它们:

Const olAppointmentItem As Integer = 1
Set olAppt = olApp.CreateItem(olAppointmentItem)

wdPASTERTF相同,根据WdPasteDataType enumeration (Word)也是1

Sub CreateNewOutlookAppointment()        
    Dim olApp As Object
    Set olApp = CreateObject("Outlook.Application")

    Dim olAppt As Object
    Set olAppt = olApp.CreateItem(1) 'you cannot use `olAppointmentItem` in late binding (unless you declare it as constant)

    Dim myInspector As Object
    Set myInspector = olAppt.GetInspector
    myInspector.Activate

    With olAppt
        .Subject = "Review" & ", " & ThisWorkbook.Sheets("Other Data").Range("P23").Value
        ThisWorkbook.Sheets("Templates").Range("M202:M223").Copy
        .Display
        .GetInspector.WordEditor.Windows(1).Selection.PasteAndFormat 1 'wdPASTERTF = 1

        .Attachments.Add Environ("temp") & "\" & _
                         ThisWorkbook.Sheets("Other Data").Range("AK2").Value & ", " & _
                         "Bid review" & ".pdf"
    End With

    Application.SendKeys ("%HOM")
End Sub