Search code examples
vbaoutlookoutlook-2010

Programmatically adding References to Outlook 2010 in VBA


I have a macro for Outlook that, in part, edits the content of an email or calendar item, which requires that the "Microsoft Word 14.0 Object Library" Reference is added. I know how to do this in Excel ActiveWorkbook.VBProject.References.AddFromGuid(), but I can't find any information on doing this in Outlook.

Is it possible?

Sample code per Remou:

Sub CreateNotesEmailFromAppointment()
  Dim oMeeting As AppointmentItem
  Dim oEmailTemplate As Outlook.MailItem
  Dim oEmailWordDoc As Word.Document

  If Application.ActiveInspector.CurrentItem.Class = olAppointment Then
    Set oMeeting = Application.ActiveInspector.CurrentItem
    Set oEmailTemplate = Application.CreateItemFromTemplate(PathToTemplateFile)
    oEmailTemplate.Display
    Set oEmailWordDoc = Application.ActiveInspector.WordEditor

    With oEmailWordDoc.Content.Find
        .Text = "<Date>"
        .Replacement.Text = Month(oMeeting.Start) & "/" & Day(oMeeting.Start)
        .Execute Replace:=wdReplaceAll
    End With
    'More editing and formatting of oEmailWordDoc follows'
  End If
End Sub

Solution

  • Consider late binding:

    Dim wd As Object
    
    Set wd = CreateObject("Word.Application")
    wd.Visible = True
    wd.Documents.Open "C:\Docs\Temp.doc"
    

    If an instance of Word may be running:

    On Error Resume Next
    Set wd = GetObject(,"Word.Application")
    
    If Err.Number <> 0 Then
       Set wd = CreateObject("Word.Application")
    End If
    
    wd.Visible = True
    

    This is for 2002, but is a better reference that the more recent ones: http://support.microsoft.com/kb/307216

    How about a different approach that does not use word but rather the HTMLBody of the template:

      Dim oMeeting As AppointmentItem
      Dim oEmailTemplate As Outlook.MailItem
    
      If Application.ActiveInspector.CurrentItem.Class = olAppointment Then
        Set oMeeting = Application.ActiveInspector.CurrentItem
        Set oEmailTemplate = Application.CreateItemFromTemplate(PathToTemplateFile)
        oEmailTemplate.Display
        oEmailTemplate.HTMLBody = _
           Replace(oEmailTemplate.HTMLBody, "&lt;date&gt;", Month(oMeeting.Start) _
              & "/" & Day(oMeeting.Start))
      End If