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

Thanks for allowing me to seek your wisdom. I have Word documents with headers and footers in them. I am able to use Win32::OLE to search and replace text in the primary header, no problem. How do I make sure that I access all the headers in the document so that I am assured to replace text in all of them?

Also, how do I access comments through Win32::OLE? I also want to search and replace in all the comments, if possible.

Thanks
  • Comment on Win32::OLE and Word: accessing all headers and comments

Replies are listed 'Best First'.
Re: Win32::OLE and Word: accessing all headers and comments
by poj (Abbot) on Mar 17, 2019 at 20:15 UTC

    Loop through the collection of objects with 'in'

    #!perl use strict; use Win32::OLE('in'); use Win32::OLE::Const "Microsoft Word"; Win32::OLE->Option(Warn => 3); my $Word = Win32::OLE->new('Word.Application'); $Word->{Visible} = 1; my $Doc = $Word->{Documents}->Open('c:/temp/HelloWorld.docx'); for my $Section (in $Doc->Sections){ printf "Section %d\n",$Section->{Index}; for my $Header (in $Section->Headers()){ printf "Header %d - %s\n",$Header->{Index}, $Header->Range->{Text}; } for my $Footer (in $Section->Footers()){ printf "Footer %d - %s\n",$Footer->{Index}, $Footer->Range->{Text}; } } for my $Comment (in $Doc->Comments){ printf "Comment %d - %s\n",$Comment->{Index},$Comment->Range->Text } undef $Doc; undef $Word;

    It gets complicated if your header/footers include text inside shapes !

    poj
      I was facing a similar issue and your code sample was just the thing I needed. For my system (Windows 10 -- Office 2016) I had to make Win32::OLE::Const more generic, and I added "close" and "quit" to close the document and end MS Word. Thank you poj for the sample code.
      use Win32::OLE::Const "Microsoft Office .* Object Library"; # Close document $Doc->Close(); undef $Doc; # Close MS Word $Word->Quit(); undef $Word;

      "It's not how hard you work, it's how much you get done."