问题
I would like to use Perl to run a macro in an already open Excel workbook.
The following code works if I just want to open a workbook and run a macro:
#!C:\Perl\bin\perl.exe
use strict;
use Win32::OLE;
my $Excel = Win32::OLE->new('Excel.Application') or die;
$Excel->Workbooks->open('M:\Programs\MyExcelFile.xls');
$Excel->run('Book1!ChartData');
$Excel->quit;
But how do I operate on an open workbook?
回答1:
Use GetActiveObject
. From the docs:
Here is a simple Microsoft Excel application.
use Win32::OLE;
# use existing instance if Excel is already running
eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
die "Excel not installed" if $@;
unless (defined $ex) {
$ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
or die "Oops, cannot start Excel";
}
来源:https://stackoverflow.com/questions/12961662/how-do-i-use-perl-to-run-a-macro-in-an-already-open-excel-workbook