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

Good day Monks. I am trying to perform a merge & center operation on a set of columns in an Excel spreadsheet via Win32::OLE. I have learned that the way to find out how to do new things in OLE is to record a macro to translate the VB commands into Perl/Win32::OLE statements. Here is the macro code for exactly what I wanted to do:
Sub Macro1() ' ' Macro1 Macro ' ' Range("B1:Q1").Select With Selection .HorizontalAlignment = xlCenter .VerticalAlignment = xlBottom .WrapText = False .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With Selection.Merge End Sub
Here is my code to implement:
use Win32::OLE qw(in with CP_UTF8); Win32::OLE->Option(CP => CP_UTF8); use Win32::OLE::Const 'Microsoft Excel'; use Win32::OLE::Variant; $Win32::OLE::Warn = 3; my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32: +:OLE->new('Excel.Application', 'Quit'); # get already active Excel $Excel->{'Visible'} = 1; my $Book = $Excel->Workbooks->Open('foo.xlsx'); my $Sheet = $Book->Worksheets(1); $Sheet->Range("B1:Q1")->Merge(); $Sheet->Range("B1:Q1")->{HorizontalAlignment} = 'xlCenter';
The merge works correctly! Alas, the center does not:
Win32::OLE operating in debugging mode: _Unique => 1 OLE exception from "Microsoft Excel": Unable to set the HorizontalAlignment property of the Range class Win32::OLE(0.1709) error 0x80020009: "Exception occurred" in PROPERTYPUT "HorizontalAlignment" at C:\Users\boss\Dropbox C:\t +mp\merge-center.pl line 11.
Does anyone know how to fix it?

Replies are listed 'Best First'.
Re: Win32::OLE Excell Merge & Center
by pryrt (Abbot) on Aug 06, 2023 at 23:31 UTC
    The value of VBA's xlCenter is not the string 'xlCenter'. You will want to see Win32::OLE::Const for how to extract the xl-constants.

    Based on your last example, I think you would need to add

    use Win32::OLE::Const; my $xlConstants = Win32::OLE::Const->Load($Excel);
    and then change to
    $Sheet->Range("B1:Q1")->{HorizontalAlignment} = $xlConstants->{xlCente +r};

    (untested: sorry, I don't have Excel on this machine)

      That did it...thanks!
Re: Win32::OLE Excell Merge & Center
by karlgoethebier (Abbot) on Aug 08, 2023 at 10:34 UTC