You're close - very close - but no nicotine patch. You are trying to manipulate the address as a string to get the number of the column, or at least that's how it appears to me. I think you will find it easier to use the column number directly, as shown in the code below:
use strict;
use warnings;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Excel';
my $xl = Win32::OLE->new('Excel.Application');
$xl->{EnableEvents} = 0;
$xl->{Visible} = 1;
my $wb = $xl->Workbooks->Add;
my $sht = $wb->Sheets(1);
$sht->Cells(3,3)->{Value}="Here";
my $penultimate_column = $sht->UsedRange->SpecialCells(xlCellTypeLastC
+ell)->{Column} - 1;
print $penultimate_column;
There can be issues with UsedRange if you need to delete rows or columns within the range, but my tests indicate that the issues that exist in VBA don't exist in Perl. That's quite likely, as there are many things that can happen to the used range. See this as a starting point if you want to get all technical. Note that you don't have to use Range($address) with a string address to point to a cell. It's equally valid to use Cells($row, $col) with the row and column as numbers. Some things are far easier this way.
It ought to be even simpler to use UsedRange->Columns->{Count} to give the number of columns, but for some reason I couldn't get that working, possibly because it's gone midnight.
Regards,
John Davies |