2009-09-15 329 views
4

編輯:如果你有一個VBA的例子,我會接受它。我只是想了解如何將Range對象與Tables集合一起使用來複制和粘貼多個沒有循環的表。換句話說,如何使用Tables集合來指定範圍1..lastTable?如果我能看到一個有效的VBA示例,我將介紹VBA - > Perl轉換。如何在Word中複製和粘貼一系列表格?

我正在嘗試使用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(); 

原來代碼中使用段落,沒有桌子,所以我想有些錯誤是文物從代碼(或更可能我不理解碼)。

+0

我的建議是嘗試手動執行任務,同時錄製宏,然後看所產生的VBA子程序。您應該能夠將其推廣並將其轉換爲Perlish,而不會有太多麻煩。 – 2009-09-16 15:51:44

+0

使用這種方法只是告訴我如何使用Selection來獲得一個表格,而如果我嘗試選擇多個表格,宏寫入的也是它們之間的文本,這不是我所追求的。 – romandas 2009-09-17 12:48:30

回答

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 "[email protected]\n" if [email protected]; 

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

太棒了!儘管有一個問題..是否沒有辦法從集合對象中選擇一系列對象?說,所有的表格對象,沒有任何其他文字在一個操作?我只是在問這是否可能 - 我得到的印象並非如此,或者至少它不能像我認爲的那樣工作。 – romandas 2009-09-20 18:42:48

+0

@romandas我不這麼認爲。 'Tables'集合沒有'Range'方法。 – 2009-09-20 19:17:53

+0

謝謝! +1並被接受。 – romandas 2009-09-22 01:12:05