Running an excel macro from Perl
Lhamo_rin
created: 2006-02-01 08:24:37
Is it possible to open an MS Excel file from a Perl program and run a macro? If so, does anybody have some example code? Thanks,
Re: Running an excel macro from Perl
created: 2006-02-01 08:44:53
[Lhamo_rin],

Did you use [Super Search] before posting this?
If you are using [http://www.activestate.com | ActiveState] Perl, using [mod://Win32::OLE]:
#!/usr/bin/perl
use strict;
use Win32::OLE qw(in with);
use Win32::OLE::Const;
use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3;

my $filename = 'c:\\book_with_macros.xls';
my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit');  

my $Book = $Excel->Workbooks->Open( $filename );
$Excel->Run("MYMACRONAMEHERE");
$Book->Close;
N.B. The above code is untested.
Check out [http://www.xav.com/perl/faq/Windows/ActivePerl-Winfaq12.html | this article] for more examples, including [http://www.xav.com/perl/faq/Windows/ActivePerl-Winfaq12.html#convert_vba | How do I convert a VBA macro to Perl?], which may interest you.

Hope this helps.

Martin
Re: Running an excel macro from Perl
created: 2006-02-01 08:51:51

I patched the following together from the examples in the Activestate documentation in the section "Using OLE with Perl", under the subheading "How do I run a Macro in Microsoft Excel". It works quite well.

This will only work if you run it on a Windows system with Excel installed

	
use strict;
use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Excel';

my $filename = 'book1.xls';
my $Excel = Win32::OLE->GetActiveObject('Excel.Application')|| Win32::OLE->new('Excel.Application', 'Quit');  # use the Excel application if it's open, otherwise open new

my $Book = $Excel->Workbooks->Open( $filename ); # open the file
$Excel->Run("macro_name");
$Book->Save; #optional - save any changes made by the macro
$Book->Close;
Re: Running an excel macro from Perl
created: 2006-02-01 11:37:29

Hi,

Take a look at this excellent tutorial Using Win32::OLE and Excel - Tips and Tricks

Regards,
Murugesan Kandasamy
use perl for(;;);

perlmonks.org content © perlmonks.org and Lhamo_rin, marto, murugu, terce

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03