How Can I Save Word Documents as Text Files By Using a Script?

ScriptingGuy1

Hey, Scripting Guy! Question

Hey, Scripting Guy! I have a series of Word files. I would like to open each of these files and save them as plain-text files. Is there a way to do that using a script?

— CG

SpacerHey, Scripting Guy! AnswerScript Center

Hey, CG. Yes, you can do this quite easily with a script; in fact, with very few exceptions anything you can do within a Microsoft Office program you can do by using a script. Within Word, you can do a File – Save As and save a Word document as a text file. And you can do the very same thing using a script. In fact, you can do it using this script:

Const wdFormatText = 2

Set objWord = CreateObject(“Word.Application”) Set objDoc = objWord.Documents.Open(“c:\scripts\mylog.doc”) objDoc.SaveAs “c:\scripts\mylog.txt”, wdFormatText

objWord.Quit

We start off by creating a constant named wdFormatText and assigning it the value 2; this constant will be used to tell Word we want our new file saved as a text file. We then create an instance of Microsoft Word, and use the Open method to open the file C:\Scripts\MyLog.doc. After the document is open, we need just one line of code to save the Word document as a text file:

objDoc.SaveAs “c:\scripts\mylog.txt”, wdFormatText

As you can see, we call the SaveAs method, and we pass it two parameters: 1) C:\Scripts\MyLog.txt, which is the path for our new text file; and, 2) wdFormatText, which tells Word to save the file as plain text. That’s it. We then use the Quit method to close our instance of Word.

Two quick notes. First, you won’t see any of this happening on screen; that’s because, by default, Word runs in an invisible window any time you call it from a script. If you’d prefer to see it pop up on the screen, save the file, and then disappear, use this code instead:

Const wdFormatText = 2

Set objWord = CreateObject(“Word.Application”) objWord.Visible = TRUE Set objDoc = objWord.Documents.Open(“c:\scripts\mylog.doc”) objDoc.SaveAs “c:\scripts\mylog.txt”, wdFormatText

objWord.Quit

The only difference here is that we’ve set the Visible property to TRUE.

Second, you can save your Word documents in formats other than plain text. For example, to save a Word document as an HTML file, use the constant wdFormatHTML (value = 8); to save a Word document as XML, use the constant wdFormatXML (value = 11).

And at the risk of sounding like an informercial, if you’d like to know more about scripting and Microsoft Office you might want to check out the Scripting Week 2 webcast If You Want Something Done Right, Let Microsoft Office Do It For You.

0 comments

Discussion is closed.

Feedback usabilla icon