More Ways To Open A Doc

As the Perl guys like to say and what I tell my girlfriend, there is more than one way to do it. This is also true for a simple task such as opening a Word document using Visual Basic script. The following code opens a MS Word document:

Sub OpenWord(fileName)
    Set Word = WScript.CreateObject("Word.Application")
    Word.Visible = True
    Set doc = Word.Documents.Open(fileName)
End Sub

I have seen some issues with such code if the word document has a mail merge data source associated with it and you try to execute it (see Word Mail Merge).

doc.MailMerge.Execute True

Trying to execute the mail merge generates a ‘This method or property is not available because the document is not a mail merge main document.’ But I know this is wrong because double clicking on the file reveals a data source associated with the document. Another way to open a word document and circumvent this issue is to use the run command such as:

Sub OpenWord(fileName)
    Set WshShell = WSCript.CreateObject("WScript.Shell")
    WshShell.Run fileName, 8, False
End Sub

In fact, the file name could be any file type and this code will try to open it up with its default application. Just to compare some code, this is the code you can use to open an Excel document:

Sub OpenExcel(fileName)
    Set Excel = WScript.CreateObject("Excel.Application")
    Excel.Visible = True
    Excel.Workbooks.Open(fileName)
End Sub