in reply to Win32 OLE Word Add Password?

Use The Macro Recorder, Luke (Re: Using Win32::OLE and Excel - Tips and Tricks)

Replies are listed 'Best First'.
Re^2: Win32 OLE Word Add Password?
by cormanaz (Deacon) on Sep 27, 2016 at 21:04 UTC
    I was thinking that was a brilliant idea, but apparently the Macro recorder does not record this operation. Here's what it yielded for code when I recorded.
    Sub pwadd() ' ' pwadd Macro ' ' End Sub

    Maybe what I want to do is not possible?

      So I only researched this problem under Perl, forgetting that you have to hunt around under VB to find answers like this. Turns out it is possible, and easier than I imagined.
      #!/usr/bin/perl -w use Win32::OLE; use Win32::OLE::Const; my $wd = Win32::OLE::Const->Load("Microsoft Word 14.0 Object Library") +; my $word = Win32::OLE->GetActiveObject('Word.Application') || Win32::OLE->new('Word.Application','Quit') or die Win32::OLE->LastError(); $word->{Visible} = 1; $filename = 'foobar.doc'; $pw = 'foobar'; $savename = 'foobarsave.doc'; my $doc = $word->Documents->Open($docname) or die Win32::OLE->LastError(); $doc->SaveAs( { FileName => $savename, Password => $pw}); $doc->close; $word->close;
      However, there are some hitches. There is apparently no way to just save the same file with a password, or if there is I couldn't find it. If you execute the SaveAs statement above with the same filename nothing happens--i.e. there is no error, nothing gets saved, and no password is added. You have to save it with a different name like I did in the example code. It might work if you changed the file in some way, like adding a space at the end, but I didn't try this.