in reply to Win32::OLE and Excel: Iterating when certain row numbers are missing
A quick first impression: your approach is never going to work. In your ### Do some stuff block, you are inserting a row. This will create the same problem as deleting a row, something I have analysed in RFC Tutorial - Deleting Excel Rows, Columns and Sheets. Start at the end and work backwards and you will eliminate at least one of your problems.
Almost immediate update: the rows are numbered sequentially in every implementation of Excel (and every other spreadsheet - dozens) I have seen. However, rows and columns may be hidden. If they are hidden, that is from the human eye, not VBA or Perl. Your code will go from row 1 to row 2 regardless of whether row 2 is visible to you.
Update 2: some code. Update 3 changed the code to include a demonstration of testing whether a row is hidden.
use strict; use warnings; use Win32::OLE; my $xl = Win32::OLE->new('Excel.Application'); $xl->{Visible} = 1; my $wb = $xl->Workbooks->Add; # Make sure there is precisely 1 sheet for my $nSht (2..$wb->Sheets->{Count}) { $wb->Sheets(2)->Delete; } # Put some data in my $sht = $wb->Sheets(1); $sht->Cells(1, 1)->{Value} = "A"; $sht->Cells(2, 1)->{Value} = "B"; $sht->Cells(3, 1)->{Value} = "C"; # Hide row 2 $sht->Cells(2, 1)->EntireRow->{Hidden} = 1; # Process 3 rows, demonstrating a bug for my $row (1..3) { if ("A" ne $sht->Cells($row, 1)->{Value}) { $sht->Cells($row + 1, 1)->EntireRow->Insert; $sht->Cells($row, 1)->EntireRow->Copy($sht->Cells($row + 1, 1) +); } } use feature 'say'; for my $row (1..5) { if ($sht->Cells($row, 1)->EntireRow->{Hidden}) { say "Row $row is hidden"; } }
Run this code and you will see three hidden rows. This is because row 2 (B) has been copied to row 3. After that, row 3 (a copy of B) has been copied to row 4. This is the loop error bug I mention in my post about deleting rows.
To reveal the rows, select rows 1 to 5, the two visible rows and the three hidden ones. Doing this with the mouse can be awkward, but I always prefer the keyboard anyway. Alt-H (Home), O (Format), U (Hide & Unhide), O (Unhide Rows) will show the three copies of what was row 2. If you are using a version with the old menu tree, it's Alt-O, R, U.
Regards,
John Davies
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Win32::OLE and Excel: Iterating when certain row numbers are missing
by ownlifeful (Beadle) on Jun 21, 2021 at 14:55 UTC | |
by davies (Monsignor) on Jun 21, 2021 at 15:01 UTC | |
by Corion (Patriarch) on Jun 21, 2021 at 15:03 UTC |