Brian Ross
Brian Ross

Reputation: 25

Outlook VBA only works if a Word Document is Open in Background

This isn't a crisis, because the script actually works just fine, but I need to implement it for an office wide process and I expect this issue will cause a bit more confusion with the less tech-savvy.

The following is intended to replace common citations that we use with links to the website where they can be found. So a reference to policy AP&P-X-A-1-100 automatically becomes a link to APP-X-A-1-100_issuance.shtml when the user hits a button.

The problem is, it only works if there's an open Word document in the background. If Word isn't open, I get one of three errors: "The Remote Server Machine does not exist or is not available" or "Automation Error: the remote call procedure failed" or "ActiveX Component Cannot Create Object". If try three times in a row, I can get any permutation of those three. I've never had revolving errors like this.

Any idea why Word is required for this to run?

Sub CitationPolicy()

Dim myInspector As Outlook.Inspector
Dim myObject As Object
Dim myItem As Outlook.MailItem
Dim rngStory As Word.Range
Dim myDoc As Word.Document
Dim mySelection As Word.Selection
Dim strItem As String
Dim strItem2 As String
Dim strLink As String

    Set myInspector = Application.ActiveInspector
    Set myObject = myInspector.CurrentItem
    Set myDoc = myInspector.WordEditor
    Set mySelection = myDoc.Application.Selection

For Each rngStory In ActiveDocument.StoryRanges
    With mySelection.Find
        .Text = "AP&P-*-[0-9]{3}"
        .MatchWildcards = True
        .Replacement.Text = ""
        .Wrap = wdFindContinue

              While mySelection.Find.Execute
              strItem = mySelection.Text
              strItem2 = Replace(strItem, "AP&P", "APP")

              mySelection.Hyperlinks.Add Anchor:=mySelection.Range, _
              Address:="http://www.oursite.com/" & strItem2 & "_issuance.shtml", _
              TextToDisplay:=strItem
              Wend

    End With

Next rngStory


End Sub

Upvotes: 1

Views: 584

Answers (1)

Krish
Krish

Reputation: 5917

Thats because you are referencing the WORD Application. Outlook uses Word engine as word-editor but this has to be referenced as MailItem.GetInspector.WordEditor. Otherwise you are forced to create Word application or in your case work only if a word application is running.

Maybe have a look at this: msdn.microsoft.com/en-us/library/dd492012(v=office.12).aspx

Hope this helps.

Upvotes: 1

Related Questions