首页 > 解决方案 > 将范围指向表格单元格的末尾

问题描述

在 Perl CGI 中,使用 Win32::OLE,我需要在表格单元格中插入几行文本,但要一行一行地插入。

我使用的不同对象是:

这是我的代码,它可以正常工作:

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();
}

当我尝试将样式应用于每个文本行时,就会出现我的问题。

由于我不想设置整个单元格的样式,而是要插入的行的样式,所以我尝试了这个(样式存储在@ly_styles数组中):

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.

标签: perlms-wordwin32oleword-table

解决方案


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.


推荐阅读