perlms-wordwin32oleword-table

Pointing a range at the end of a table cell


In a Perl CGI, using Win32::OLE, I need to insert several text lines in a table cell, but one by one.

The different objects I use are :

Here's my code, which works properly:

for (my $ii = 0; $ii <= $#ly_lines; $i++)
{
    my $lo_range = $lo_table->Cell($li_row, $li_col)->Range;
    $lo_range->InsertAfter($ly_lines[$ii]);

    $lo_range = $lo_table->Cell($li_row, $li_col)->Range;
    $lo_range->InsertParagraphAfter();
}

My problem happens when I try to apply a style to each one of the text lines.

Since I don't want to set the style of the entire cell but of the line I'm about to insert, I tried this (the styles being stored in the @ly_styles array):

for (my $ii = 0; $ii <= $#ly_lines; $i++)
{
    my $lo_range = $lo_table->Cell($li_row, $li_col)->Range;
    $lo_range->Collapse(wdCollapseEnd);

    $go_document->Styles->Add($ly_styles[$ii]);
    $lo_range->{'Style'} = $ly_styles;
    $lo_range->InsertAfter($ly_lines[$ii]);

    $lo_range = $lo_table->Cell($li_row, $li_col)->Range;
    $lo_range->Collapse(wdCollapseEnd);

    $lo_range->InsertParagraphAfter();
}

With this loop, the text lines read in a reversed order and in the cell next to the one I want!

It seems that the Collapse(wdCollapseEnd) command doesn't set the range to the end of the aimed cell, but to the beginning of the next one.

Does anyone know how to fix this? Thanks in advance.


Solution

  • You're on the right track.

    Immediately after wdCollapseEnd try moving the range backwards by a character:

    $lo_range->MoveEnd(wdCharacter, -1)
    

    The "why" is a bit arcane and I'm not sure if what I imagine is the reason is is correct... What I believe is the reason is that collapsing the Range puts the focus at the beginning of the next cell. Think of it as if the entire cell were selected and pressing right-arrow moved to the next cell instead of at the end of the text in the selected cell. So it's necessary to move back one character (like pressing left-arrow) to get to the end of the original cell.

    Range has MoveEnd and MoveStart. Using a positive number with MoveStart or a negative number with MoveEnd will effectively move the entire Range without including additional content. A negative value with MoveStart or a positive value with MoveEnd will extand the Range to include new content. Again, think of it like using the arrow keys, but this time with Shift held down to extend the selection. There are various parameters (WdUnits Enumeration) that can be used with these methods that work with objects such as cells, paragraphs, etc. The list can be found in the Word Language Reference.