Ask:
Hey, scripting guy!. I have a series of Word files. I want to open each of these files and save them as plain text files. Is there a way to do this by using a script?
--CG
For:
Hello, CG. Yes, it's easy to do this with a script. In fact, with very few exceptions, what you can do in Microsoft Office programs can be done in almost a single script. In Word, you can use file – Save As to save a Word document as a text file. You can also use a script to do the same thing. In fact, you can use the following script to do this:
Copy Code code as follows:
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 first create a constant named "Wdformattext," and then assign the value 2 to it; This constant will be used to tell Word we want the new file to be saved as a text file. Then we create a Microsoft Word instance and use the Open method to open the file C:\Scripts\MyLog.doc. Once the document is open, we need only one line of code to save this Word document as a text file:
Objdoc.saveas "C:\scripts\mylog.txt", Wdformattext
As you can, we call the "SaveAs method", and we pass it two parameters:1) C:\Scripts\MyLog.txt, which are the path for O ur new text file; And, 2) Wdformattext, which tells Word to save the file as plain text. That's it. Then we use the "Quit" method to close the Word instance.
Two important things to note. First, you don't see anything happening on the screen because, by default, whenever you call Word from a script, it will run in an invisible window. If you want to see it pop up on the screen, save the file, and then disappear, use the following code:
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 is that we set the "Visible" property to TRUE.
Second, you can save a Word document in a format other than plain text. For example, use constant wdformathtml (value = 8) to save Word documents as HTML files, and use constant wdformatxml (value = 11) to save Word documents as XML files.