I am trying to open a csv file and copy the data from within it to paste it into a tab in an already constructed excel (2016) workbook.
my problem appears to be accessing the csv file properly. Here is my code
use utf8;
use Cwd;
use warnings;
use strict;
use Win32::OLE;
use Win32::OLE qw(in with);
use Win32::OLE::Const "Microsoft Office .* Object Library";
my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit');
$Excel->{Visible} = 0;
$Excel->{DisplayAlerts}=0;
my $XLSX_LOG_IN = "book1.xlsx";
my $Book_In = $Excel->Workbooks->Open("$XLSX_LOG_IN") or die "Excel Logfile Workbook not opened - Ensure file 'book1.xlsx' is in the working directory\n";
my $csv_in = $Excel->Workbooks->Open("$csv") or die "Excel Logfile Workbook not opened - Ensure file \"$csv\" is in the working directory\n";
my @s_ins = in $csv_in->worksheets;
my $s_in = $s_ins[0];
my $name = $csv_in->Worksheets($s_in)->{Name};
print "$s_in - sheet I'm trying to open\n";
print "$name - sheet I'm trying to open\n";
my $res_sheet = $csv_in -> Worksheets("$name");
my $last_row = $res_sheet -> UsedRange -> Find({What => "*", SearchDirection => 2, SearchOrder => 1}) -> {Row};
my $last_col = $res_sheet -> UsedRange -> Find({What => "*", SearchDirection => 2, SearchOrder => 2}) -> {Column};
my $range = "A1:".$last_col.$last_row;
$res_sheet->range($range)->copy();
my $ResReport = $Book_In -> Worksheets("ModelReserveReport");
$ResReport->range('A1')->Select();
$ResReport->paste();
$csv_in->Close();
I keep getting the following error Win32::OLE(0.1712) error 0x8002000b: "Invalid index"
I think I am either not pointing excel to the right name of the worksheet or I have the method for finding the last row and column wrong but I'm struggling to work out how to fix either. Can anyone spot my mistake?
I fixed this by editiing my last 6 lines of code
I made the selection on the source sheet
my $range = "A1:CZ".$last_row;
$res_sheet->range($range)->copy();
and removed the selection before pasting my data
my $ResReport = $Book_In -> Worksheets("ModelReserveReport");
$ResReport->paste();
$csv_in->Close();
The copy/paste now works.
User contributions licensed under CC BY-SA 3.0