perlms-wordwin32ole

How to modify the column widths of a Word table using Perl?


Using Perl with the Win32::OLE module I am attemping to insert a table into a Microsoft Word document and then modify the column widths. I can insert a table without any trouble, but modifying the column widths is proving more difficult. After creating a macro and trying to translate the VBA into Perl, here is what I have:

my $word = Win32::OLE->new('Word.Application', sub {$_[0]->Quit;});
my $doc = $word->Documents->Open('myfile.doc');

### Code to find and select a tag to replace with a table goes here ###

my $table = $doc->Tables->Add($word->Selection->Range, 4, 4);
$table->Columns(1)->{PreferredWidthType} = wdPreferredWidthPoints;
$table->Columns(1)->{PreferredWidth} = 200;

Unfortunately this gives a "Can't use an undefined value as a HASH reference" error on the final two lines. I've tried several other variations on this but none have worked, and Google hasn't helped either. I'd really appreciate an answer as to how to do this.

Thanks.


Solution

  • After some trial and error I found that this did the job:

    $table->Rows(1)->Select;
    $word->Selection->Columns(1)->{Width} = 200;
    

    It was sufficient to resize just the columns on row 1, and this affected all other rows. It's easy when you know how!