2008-09-04

Convert Files to Word Documents with a Script

If you've ever needed to convert one or many garbled RTF files into a readable Word document you will appreciate this little script. Instead of having to go to each file, open it in Word, and save it into the .DOC format manually you can use this script to enumerate an entire folder of files and convert them into Word documents.

The script uses Word's API and a file system object to open each file, save it into the Word 2003 .DOC format and close it.

For my purposes, I only wanted to convert .RTF files because I was running it against a folder with .PDF and other file types. You can easily alter the file type or remove this check by deleting the If statement on line 36 - "If LCase(Right(objFile,3)) = "rtf" Then". Just make sure you leave what's inside the If block alone.

Download Link





'------------------------------
'Author: Christopher Maddalena
'Date: October 23, 2007
'Purpose: Convert garbled RTF files into Word .DOCs.
'How: This script enumerates through a folder specified as strFolder
' for every file present, opens the files and save them as .DOCs
' by using Word's API.
'------------------------------

Option Explicit
Call Main()
WScript.Quit(0)

On Error Resume Next

Sub Main
Dim objWord, objFileSystem, objSrcFolder, objFile, objDoc, objSelection
Dim strFolder, strFile, strDOC, colFiles, File

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objFileSystem = CreateObject("Scripting.FileSystemObject")

strFolder = "C:\Test" 'Put your folder's path here!

Set objSrcFolder = objFilesystem.GetFolder(strFolder)
Set colFiles = objSrcFolder.Files

For Each File In colFiles
Set objFile = objFileSystem.GetFile(strFolder & "\" & File.Name & "\")

strFile = objFile.Path

strDOC = objFileSystem.BuildPath(objFile.ParentFolder,objFileSystem.GetBaseName(objFile) & ".doc")

If LCase(Right(objFile,3)) = "rtf" Then
Set objDoc = objWord.Documents.Open(strFile)
Set objDoc = objWord.ActiveDocument
Set objSelection = objWord.Selection

'Save actibe document as the default Word .doc and close it
objDoc.SaveAs strDOC, 0
objDoc.Close
End If
Next
'Exit Word
objWord.Quit
End Sub

No comments: