none
Opening Word from Outlook, starting macro via command line; problem if Word already opened RRS feed

  • Question

  • Using the following code from Outlook to open a text file in Microsoft Word and run a macro:

    Dim wd As Object
    Dim strWord As String, strDoc As String
    Dim intSection As Integer
    Dim intTries As Integer
    Dim strFullPathAndFileName As String
    
        ' Set full path and filename
        strFullPathAndFileName = "C:\filename.txt"
        Call ProcessFile(strFullPathAndFileName)
    
        strWord = "C:\Program Files (x86)\Microsoft Office\Office12\WinWord.Exe"
        Shell """" & strWord & """ /mMyMacro", vbMaximizedFocus
           
        intSection = 1 ''attempting GetObject...
        Set wd = GetObject(, "Word.Application")
        intSection = 0 ''resume normal error handling
        wd.Documents.Open strFullPathAndFileName
        Set wd = Nothing

    Which works just fine... as long as there is not already a Word window open. If that is the case, then the macro begins in a *blank* MS Word window and the target file opens in another "instance" of MS Word.

    How can I avoid this? Should I test for Word already being open or is there a way to "force" the macro to run in the window that I want it to run in?

    Thanks.

    Monday, January 28, 2013 1:47 PM

Answers

  • Try this:

        Dim wd As Object
        Dim doc As Object
        Dim strDoc As String
        Dim intSection As Integer
        Dim intTries As Integer
        Dim strFullPathAndFileName As String
    
        ' Set full path and filename
        strFullPathAndFileName = "C:\filename.txt"
        Call ProcessFile(strFullPathAndFileName)
    
        intSection = 1 ''attempting GetObject...
        On Error Resume Next
        ' Try to refer to running instance of Word
        Set wd = GetObject(, "Word.Application")
        ' If Word wasn't running...
        If wd Is Nothing Then
            ' ... start Word
            Set wd = CreateObject("Word.Application")
            If wd Is Nothing Then
                MsgBox "Can't start Word!", vbExclamation
                Exit Sub
            End If
        End If
        On Error GoTo 0
        intSection = 0 ''resume normal error handling
    
        ' Run macro
        wd.Run "MyMacro"
    
        ' Open text file
        Set doc = wd.Documents.Open(strFullPathAndFileName)
        '...
        Set wd = Nothing


    Regards, Hans Vogelaar

    Monday, January 28, 2013 2:09 PM