如何在Word中复制和粘贴一系列表格?

时间:2009-09-15 20:41:31

标签: perl range copy-paste word-vba win32ole

编辑:如果你在VBA中有一个例子,我会接受它。我只是想了解如何将Range对象与Tables集合一起使用来复制和粘贴多个表而不进行循环。换句话说,如何使用Tables集合指定1..lastTable的范围?如果我能看到一个有效的VBA示例,我将使用VBA - > Perl转换。

我正在尝试使用Perl的Win32::OLE模块(通过Dave Roth的优秀书籍)来自动完成我需要在某些Word文档上重复执行的几项任务。但是,本书(以及大多数Web示例)倾向于使用Excel作为示例,因此我不确定如何使用Tables集合对象进行有效复制和粘贴。

以下是我的代码片段:

my $originalDoc = $MSWord->Documents->Open('C:\Perl\testDocument.doc');
my $newDoc = $MSWord->Documents->Add;
my $selection = $MSWord->Selection(); # this may be spurious

my $Count = int( $originalDoc->Tables()->{Count} );
my $range = $originalDoc->Tables()->Range( { Start => $originalDoc->Tables(1)->{Range}->{Start},
                                             End   => $originalDoc->Tables($Count)->{Range}->{End}
                                           } );
$range->Copy();
$newDoc->Range()->Paste();

原始代码使用段落,而不是表格,所以我假设一些错误是来自该代码的工件(或者更可能是我对该代码的不理解)。

1 个答案:

答案 0 :(得分:5)

一次复制和粘贴表格可能更可取:

#!/usr/bin/perl

use strict;
use warnings;

use File::Spec::Functions qw( catfile );

use Win32::OLE;
use Win32::OLE::Const 'Microsoft Word';
$Win32::OLE::Warn = 3;

my $word = get_word();
$word->{Visible} = 1;

my $doc = $word->{Documents}->Open(catfile $ENV{TEMP}, 'test.doc');
my $newdoc = $word->Documents->Add;

my $n_tables = $doc->Tables->Count;

for my $table_i ( 1 .. $n_tables ) {

    my $table = $doc->Tables->Item($table_i);
    $table->Select;
    $word->Selection->Copy;

    my $end = $newdoc->GoTo(wdGoToLine, wdGoToLast);
    $end->InsertBefore("\n");
    $end = $newdoc->GoTo(wdGoToLine, wdGoToLast);
    $end->Select;

    $word->Selection->Paste;
}

$doc->Close(0);
$newdoc->SaveAs('test-output.doc');

sub get_word {
    my $word;
    eval {
        $word = Win32::OLE->GetActiveObject('Word.Application');
    };

    die "$@\n" if $@;

    unless(defined $word) {
        $word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit })
            or die "Oops, cannot start Word: ",
                   Win32::OLE->LastError, "\n";
    }
    return $word;
}
相关问题