[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


Perl & Excel - how can I write and run Excel macros in Perl?

Posted on 2004-10-12
Medium Priority
Last Modified: 2012-08-14

I have a perl script that generates an Excel sheet with data.
I wont to run a macro on that data, for example, a Pivot macro.
The problem is that the Excel sheet that I've just created doesn't include the macro.
Is there a way to write the macro from Perl and then run it?


Question by:nivo_Z

Assisted Solution

alskdj80 earned 200 total points
ID: 12288193
there might be some info in this website that might help you: http://perlmonks.org/?node_id=153486

Author Comment

ID: 12288629
This page only explains how to run macros that are already exist in the sheet.

Accepted Solution

CobolDotNet earned 800 total points
ID: 12294695
What a wonderful idea:  Writing code to write more code in another application!

What we want is to put a macro in an Excel workbook from a program.  We can do this by having the Perl code use OLE as alskdj80 pointed out.

I found this: http://support.microsoft.com/default.aspx?scid=kb;EN-US;303871  (VB.NET)
and this: http://support.microsoft.com/kb/194611 (VB 6)

Although that is for VB, the same applies to making the macro code in the target Excel workbook from perl.    The relevant lines from the second link above are this:
       ' Add a module
       Dim xlmodule As Object 'VBComponent
       Set xlmodule = xlbook.VBProject.VBComponents.Add(1)  'vbext_ct_StdModule

       ' Add a macro to the module...
       Dim strCode As String
       strCode = _
          "sub MyMacro()" & vbCr & _
          "   msgbox ""Inside generated macro!!!"" " & vbCr & _
          "end sub"
       xlmodule.CodeModule.AddFromString strCode
<end quote>

The module object is referenced from Microsoft Visual Basic for Applications Extensibility Library (VBE6EXT.OLB).  So in our Perl code, we have to get the right reference, set up the module object, put the macro in a string, and then pass along the string to the module.  Sounds confusing enough.

[Aside: I ran the code in the VB6 link on a Win2K machine, and did not have to set the explicit reference to the Extensibility Library despite the instructions from the KB article.  Your results may vary.]

In Perl, it should run something similar to this:
    #! usr/bin/perl

    #get the perl modules
    use Win32::OLE qw(in with);
    use Win32::OLE::Const 'Microsoft Excel';

    #Make the objects
    my $Excel = Win32::OLE->new('Excel.Application', 'Quit');
    my $Book = $Excel->Workbooks->Add();
    my $xlmodule = $Book->VBProject->VBComponents->Add(1); # vbext_ct_StdModule is the default

    #Make the module code
    my $Code = "sub MyMacro\n\tMsgBox(\"Inside generated macro!!!\nWith Perl No Less!!!!\"\nEnd Sub";

    #Put in the code
    $xlmodule->CodeModule->AddFromString = $Code;

Hope that helps.


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.


Expert Comment

ID: 12295262
Hi Nivo

U can do precisely as CobolDotNet has suggested. I think, thats the ONLY way. For more clear understanding it would be helpful if u tell us what does that pivot macro will do.


Author Comment

ID: 12296600

It soesn't work for me, maybe because I'm trying it from CGI?

I start the Excel like this:

   use Spreadsheet::WriteExcel;

    print "Content-type: application/vnd.ms-excel\n\n";

    my $workbook = Spreadsheet::WriteExcel->new("-");

Then I wrote:

    my $xlmodule = $worksheet->VBProject->VBComponents->Add(1); # vbext_ct_StdModule is the default

    #Make the module code
    my $Code = "sub MyMacro\n\tMsgBox(\"Inside generated macro!!!\nWith Perl No Less!!!!\"\nEnd Sub";

    #Put in the code
    $xlmodule->CodeModule->AddFromString = $Code;

      # Run the macro

Expert Comment

ID: 12297339
A CGI context shouldn't have anything to do with it; using Perl for CGI scripts generally works fine.

Also, the module object should be created from the workbook object, not the worksheet.

I did make one error:
    $xlmodule->CodeModule->AddFromString = $Code; should read
    $xlmodule->CodeModule->AddFromString ($Code);

What errors, if any, are you getting?  Can you explain a little more what you are trying?  I assume that it is a web page since you mention CGI.  Lastly, can you post more of your script so that we can better see what is happening code wise (e.g. the macro being installed, setting up the Excel workbook, etc.)?

Author Comment

ID: 12297490

Here is the full script, actually the interesting lines appear in my previous post, but here it is.
The script is invoked from a hyperlink on a web page. After the Excel opens I open the VB Editor and I cannot find the macro.

    use Spreadsheet::WriteExcel;

    print "Content-type: application/vnd.ms-excel\n\n";

    my $workbook = Spreadsheet::WriteExcel->new("-");

# Add a worksheet
    $worksheet = $workbook->addworksheet('Data');

# Add and define a format - heading
    $formathead = $workbook->addformat(); # Add a format

# Add and define a format - aligned to left
    $formatleft = $workbook->addformat(); # Add format1

# Add and define a format - heading
    $formatbold = $workbook->addformat(); # Add a format

$worksheet->set_column(3, 3,  10);


# Get records data from file
          # Open app_data.txt file      
                  if (open(FILE,"$datafile"))
                        @ALL_RECORDS = <FILE>;
                        $error="Failed to open file: $datafile";

# Print table header
  # Print the table header

    $count_col = 0;
    $count_row = 0;

      $HEADER[0] = "ID";
      $HEADER[1] = "User";
      $HEADER[2] = "Date";
      $HEADER[3] = "Status";
      $HEADER[4] = "Priority";
      $HEADER[5] = "Locked";
      $HEADER[6] = "Date Completed";
      $HEADER[8] = "Subject";
      $HEADER[7] = "Locked By";
    for ($j=0 ;$j<@HEADER; $j++)
            $worksheet->write($count_row, $count_col, "$HEADER[$j]", $formathead);

# Print table content

      for($r=0; $r<@ALL_RECORDS; $r++)
            @FP=split(/\|/, $ALL_RECORDS[$r]);

            $worksheet->write($count_row, 0, "$FP[0]", $formatleft);
            $worksheet->write($count_row, 1, "$FP[1]", $formatleft);
            $worksheet->write($count_row, 2, "$FP[2]", $formatleft);
            $worksheet->write($count_row, 3, "$FP[3]", $formatleft);
            $worksheet->write($count_row, 4, "$FP[4]", $formatleft);
            $worksheet->write($count_row, 5, "$FP[5]", $formatleft);
            $worksheet->write($count_row, 6, "$FP[6]", $formatleft);
            $worksheet->write($count_row, 8, "$FP[7]", $formatleft);
            $worksheet->write($count_row, 7, "$FP[8]", $formatleft);

### Here I try to write and run the macro

    $xlmodule = $workbook->VBProject->VBComponents->Add(1); # vbext_ct_StdModule is the default

#Make the module code
    $Code = "sub MyMacro\n\tMsgBox(\"Inside generated macro!!!\nWith Perl No Less!!!!\"\nEnd Sub";

#Put in the code

# Run the macro

Expert Comment

ID: 12302901
As far as I can tell, inserting in VBA modules is going to require Win32::OLE in Perl since you need the functionality from the VBA extensibility library.  Looking over the documentation in Spreadsheet::Excel, I don't see where that can be done.

As a crufty solution to not rewrite the entire script: Rather than direct to STDOUT with the "-" special name in the new constructor, pass a file name.  Let WriteExcel do its work.  Then call the close statement.

Now we have a file on the server, so we use OLE to do something like:
    my $Excel = Win32::OLE->new('Excel.Application', 'Quit');
    my $Book = $Excel->Workbooks->Open("C:\MyTempDir\MyExcelFile.xls");
    my $xlmodule = $Book->VBProject->VBComponents->Add(1);
    my $Code = "sub MyMacro\n\tMsgBox(\"Inside generated macro!!! With Perl No Less!!!!\"\nEnd Sub";

That should be able to put in your macro.  Last we put it to the browser by putting the file in binmode, reading it to a buffer, printing the buffer to STDOUT (which will be the browser).

Author Comment

ID: 12331481
I gave up, it doesn't work for me.
I'll try figuring it later.

Thank you all for your effort.

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question