Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Search and replace in multple MS Word documents

by Wobbel (Acolyte)
on Sep 02, 2009 at 13:10 UTC ( [id://792913]=perlquestion: print w/replies, xml ) Need Help??

Wobbel has asked for the wisdom of the Perl Monks concerning the following question:

I have to update 358 MS Word 2003 documents. Is it possible, for instance with WIN32:OLE, to search and replace certain words (case sensetive) in a "batch"?

Replies are listed 'Best First'.
Re: Search and replace in multple MS Word documents
by Corion (Patriarch) on Sep 02, 2009 at 13:19 UTC
Re: Search and replace in multple MS Word documents
by hominid (Priest) on Sep 02, 2009 at 15:16 UTC
    This is a simple example of searching and replacing case sensitive text in a MS Word document. Use a loop to handle multiple docs.
    use strict; use warnings; use Win32::OLE::Const 'Microsoft Word'; $Win32::OLE::Warn = 1; my $word = Win32::OLE->new("Word.Application"); $word->{DisplayAlerts} = 0; $word->{Visible} = 0; my $doc = $word->Documents->Open("\\YOUR\\PATH\\TO\\FILE"); my $selection = $doc->Content->Find; $selection->{Text} = "hippopotamus"; $selection->{Replacement}->{Text} = "elephant"; $selection->{MatchCase} = 1; $selection->Execute({Replace => wdReplaceAll}); $doc->SaveAs("\\YOUR\\PATH\\TO\\ALTEREDFILE"); $doc->Close; $word->Quit;
      Thanks a lot! Creating documents (xls, doc) is possible, but I was not sure if it was possible to manipulate excisting documents. Performance issues with a lot of documents? I'm very glad with the code (and it ain't VB ;-) ....)
        Performance issues with a lot of documents?
        Shouldn't be. But the specific answer depends on your performance requirements and your definition of "a lot". (358 files doesn't seem like a lot to me.) Just test and see.
        ...but I was not sure if it was possible to manipulate excisting documents.
        Corion's advice about macros is dead on. And after you have seen some of the macro code side by side with the equivalent Perl code, it gets easier to translate between the two. The Word Object Model Reference is a handy information source.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://792913]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-03-29 11:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found