Why does Perl's Win32::OLE complain about "Invalid index" for an Excel worksheet?

0

Code

# get already active Excel application or open new
my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
    || Win32::OLE->new('Excel.Application', 'Quit');  

# open Excel file
my $Book = $Excel->WorkBooks->Open($file); 

# select worksheet number. Default is 1 (you can also select a worksheet by name)
print "worksheet $worksheet\n";
my $Sheet = $Book->Worksheets($worksheet);

where $worksheet is an integer obtained as a value from a hash.

Error - 
Win32::OLE(0.1709) error 0x8002000b: "Invalid index"
    in METHOD/PROPERTYGET "Worksheets" at win32excel.pl

Any suggestions what I might be doing wrong?

windows
perl
excel
asked on Stack Overflow Oct 20, 2010 by Sumod • edited Oct 21, 2010 by brian d foy

2 Answers

2

Yes, $worksheet is probably 0. Because Microsoft's applications interface language is VB, the first index to Worksheets--as in many MS collections--is 1.

So you can test you range for sanity.

if ( $worksheet > 0 and $worksheet <= $xl->Worksheets->{Count} ) { 
    ...
}

Jmz's idea is probably not a bad way to surmount the issue.

use Win32::OLE qw<in>;

my @sheets = in $book->worksheets;
my $first_sheet = $sheets[0]; # or shift @sheets.

Thus reducing the cognitive dissonance from VB-ish to Perl.

answered on Stack Overflow Oct 20, 2010 by Axeman • edited Oct 20, 2010 by Axeman
1

Determine which sheets are available before accessing them:

use Win32::OLE qw(in);
my @sheets = in $Book->Worksheets;
answered on Stack Overflow Oct 20, 2010 by jmz

User contributions licensed under CC BY-SA 3.0