Nov 9 2005

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

Nov 2 2005

Word Mail Merge

“Learn something new every day.” That is my personal motto and I really feel that everyday I learn something new. Well, the other day I learned about MS Word’s Mail Merge capabilities. Word’s Mail Merge feature allows you to define a Word document template to be used for every row in a data source file. Your data source can be an Excel file or a Word document with a single table. Once you have a data source file you can merge it with the template using the following Visual Basic script code:

Sub OpenWord(fileName, datasource)
   Set Word = WScript.CreateObject("Word.Application")
   Word.Visible = True
   Set doc = Word.Documents.Open(fileName)
   doc.MailMerge.OpenDataSource(datasource)
   doc.MailMerge.Execute True
End Sub