Reading and Printing Word Documents in WSH
(Page 1 of 5 )
In my last article, I showed you how to connect to Microsoft Word’s OLE automation object to open and create documents. You also learned how to edit and save them. In today’s article, I’m going to take things a bit further and show you some scripting techniques that can be used to perform some more advanced functions.
We’ll begin with one of the most popular requests I receive. I’m constantly being asked how to read text from a Word document. Well, you’re in luck because I’m going to show you how—and it’s actually pretty simple.
To get started, you’ll either need to open a document or create a new one and fill it with some text. You learned how to do both in my last article so I won’t go into too much detail.
Const wdDoNotSaveChanges = 0
strDocument = "C:mydoc.docx"
Set objWord = CreateObject("Word.Application")
objWord.Visible = False
objWord.DisplayAlerts = False
objWord.Documents.Open strDocument,, True
Set objDoc = objWord.ActiveDocument
What I’ve done here is created an instance of the Word automation object, set some basic properties, and opened an existing Word document. In this example, I’ve opened the document as read-only to prevent accidentally saving any changes.
Set objRange = objDoc.Content
strContents = objWord.CleanString(objRange.Text)
Next, I set a range that includes the entire contents of the document using the Document object’s Content property. That Range object has a Text property that returns a text string containing the text of that range. I’ve gone a little further by using the Word object’s CleanString function as well. This function will remove any Word-specific formatting from the string.
objWord.Quit wdDoNotSaveChanges
MsgBox strContents
I finish up by closing the Word application and displaying the contents in a message box. Of course, you could use this text string in any way you like.
Next: Printing Word Documents >>
More Windows Scripting Articles
More By Nilpo