Lhamo_rin has asked for the wisdom of the Perl Monks concerning the following question:

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,

Replies are listed 'Best First'.
Re: Running an excel macro from Perl
by marto (Cardinal) on Feb 01, 2006 at 13:44 UTC
    Lhamo_rin,

    Did you use Super Search before posting this?
    If you are using ActiveState Perl, using 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 this article for more examples, including How do I convert a VBA macro to Perl?, which may interest you.

    Hope this helps.

    Martin
Re: Running an excel macro from Perl
by terce (Friar) on Feb 01, 2006 at 13:51 UTC

    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 i +f 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
by murugu (Curate) on Feb 01, 2006 at 16:37 UTC
Re: Running an "excel macro using GUI"?
by Ratazong (Monsignor) on Aug 27, 2009 at 14:33 UTC
    Hi!

    One further question executing Excel-Macros:

    The Excel-Macro I like to start opens a pop-up-window asking for data (the password). And it displays some buttons to select the functionality. Will I be able to execute it in a "batch"-mode from perl? E.g. by adding some parameters to the

    $Excel->Run("macro_name");
    -line? Or do I have to rewrite the excel-macros (so they run without GUI-interaction?)?

    Thanks

    Rata