views:

85

answers:

1

I have a Word document as an attachment to an email that I need to get some data out of to pass to a URL. To do this I'm saving the attachment to the local temp file, then opening the document, and then using the Word object model to pull data out of tables in the document.

I'm having a couple of problems when opening the document in VBA: firstly it's very slow because we have some corporate macro stuff that loads when Word opens; and secondly if there are any messages that ping up when Word opens (such as document recovery stuff), the code just hangs and Word is never closed.

So, my question is can I open Word in safe mode from VBA so that nothing but the bare bones document is available (because that's all I need)? Or, is there a better way of controlling Word that gets around the issues I'm having?

+2  A: 

Perhaps use shell to open in safe mode, say:

"C:\Program Files\Microsoft Office\Office11\Winword.exe" /a

Then use GetObject to get the instance.

More details:

Dim wd As Object
Dim strWord As String, strDoc As String
Dim intSection As Integer
Dim intTries As Integer

    On Error GoTo ErrorHandler

    strWord = "C:\Program Files\Microsoft Office\Office11\WinWord.Exe"
    strDoc = "C:\Docs\ADoc.doc"

    Shell """" & strWord & """ /a", vbMinimizedFocus

    ''Set focus to something other than the word document
    ''See http://support.microsoft.com/kb/238610
    Forms!MyForm.SetFocus

    intSection = 1 ''attempting GetObject...
    Set wd = GetObject(, "Word.Application")
    intSection = 0 ''resume normal error handling

    wd.Documents.Open strDoc

    ''Code here

    Set wd = Nothing

    ''Exit procedure:
    Exit Sub

ErrorHandler:
    If intSection = 1 Then
        intTries = intTries + 1
        If intTries < 20 Then
            Sleep 500 '' wait 1/2 seconds
            Resume ''resume code at the GetObject line
        Else
            MsgBox "GetObject still failing. Process ended.", _
                vbMsgBoxSetForeground
        End If
    Else ''intSection = 0 so use normal error handling:
        MsgBox Error$
    End If

For Sleep, this needs to go at the top of the module:

Private Declare Sub Sleep Lib "kernel32" _
    (ByVal dwMilliseconds As Long)

/a Starts Word and prevents add-ins and global templates (including the Normal template) from being loaded automatically.

The /a switch also locks the setting files; that is, the setting files cannot be read or modified if you use this switch.

Remou
thanks for this. haven't actually tried it yet (hence the delay in this reply) but it looks exactly like what i'm after. thanks again.
Rob Hick