Code snippets to automate MS Word

I came across some old postings asking how to use Ruby to automate
Word. These code snippets aren’t very elegant (I’m still a novice),
but they’re pretty helpful for working with batches of Word documents.

To find and replace a word or phrase in a batch of Word docs:
require 'win32ole’
msword = WIN32OLE.new(‘Word.Application’)
msword.Visible = true
msword.FileSearch.NewSearch
msword.FileSearch.LookIn = 'C:\test’
msword.FileSearch.SearchSubFolders = true
msword.FileSearch.FileName = ‘*.doc’

In VBA, the constant msoFileTypeAllFiles is 1

msword.FileSearch.FileType = 1
msword.FileSearch.Execute
countOfFoundFiles = msword.FileSearch.FoundFiles.Count
#Open all the found Word documents.
1.upto(countOfFoundFiles){|i|
@docname = msword.FileSearch.FoundFiles(i)
msword.documents.open(@docname)
#Replace the old word with the new word
msword.Selection.Find.Text = 'VBA’
msword.Selection.Find.Replacement.Text = 'Ruby’
msword.Selection.Find.Execute
msword.ActiveDocument.Save
msword.ActiveDocument.Close
}

Use this code block to save a Word doc in RTF format:
1.upto(countOfFoundFiles){|i|
@docname = msword.FileSearch.FoundFiles(i)
msword.documents.open(@docname)
@rtfname = String.new(@docname)
#Remove the .doc from the end
@rtfname.chop!
@rtfname.chop!
@rtfname.chop!
@rtfname.chop!
#Append the .rtf extension
@rtfname << ‘.rtf’
#Save the RTF file
#In VBA, the constant wdFormatRTF is 6
msword.ActiveDocument.SaveAs(@rtfname, 6)
msword.ActiveDocument.Close
}