Browse | Submit A New Snippet | Create A Package

 

MS Word document manipulation

Type:
Sample Code (HOWTO)
Category:
File Management
License:
Ruby License
Language:
Ruby
 
Description:
Some snippets written by James Toomey in this ruby-talk posting:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/60004

Versions Of This Snippet::

Cici Wirachmat
Snippet ID Download Version Date Posted Author Delete
6111.02011-04-14 15:57Cici Wirachmat
Changes since last version::
MS Word document manipulation
81.02003-08-01 01:52Tom Copeland

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :1.0

To find and replace a word or phrase in batch of worddocs:
require 'Win32ole'
msword= Win32ole.new('word.Application')
msword.Visible=true
msword.FileSearch.NewSearch
msword.FileSearch .Look in='C:/test'
msword.FileSearch .SearchSubFolders=true
msword=FileSearch .FileName='*.doc'

#In VBA, the constant msoFileTypeAllFiles is 1
msword.FileSearch.FileType=1
msword.FileSearch.Execute
count of Found Files=msword.FileSearch.FoundFiles .count
#Open All the found word documents.
1. Upto(count of FoundFiles){|i|
@docname=msword.FileSearch.FoundFiles(i)
msword.documments.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 (Count ofFoundFiles){|i|
   @docname=msword.FileSearch.FoundFiles(i)
   msword, Documents.Open(@docname)
   @rtfname=Sting.new(@docname)
#remove the doc from the end
@rtfname.Chop !
@rtfname.Chop !
@rtfname.Chop !
@rtfname.Chop !
#Append the .rtf Extension
@rtfname<<'rtf'
#In VBA, The constant wdFormat RTF is 6
msword.ActiveDocument.Save As(@rtfname. 6)
msword.ActiveDocument.Close

}
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..