I'm trying to get my Excelscript to delete unwanted rows. I think my logic should delete the rows but I'm finding that about 50% of unwanted rows disappear but some remain. I think this is related to row numbers changing as rows are deleted but I thought this wouldn't be an issue in the logic below.
Based on a comparison function earlier in the script, I can get my table to look something like this:
| Header1 | Header2 | Header3 | Header4 | Update |
|---|---|---|---|---|
| First | row | value | data | |
| Second | row | value | data | YES |
| Third | row | value | data | |
| Fourth | row | value | data | YES |
| Fifth | row | value | data |
The first part of the script works OK. Header1 (Column A) will have a value on every row. So I use that for the row count. I then get the values for the Update column but use the total row count from A because there will be some empty cells in the Update column.
I loop through the values to see which rows include YES or Update in the column to exclude the header itself. All the row numbers of the blank cells go into a 1D array.
I then thought if I start at the last entry of the array and delete the row before looping back around, all the row numbers before it will still be valid. I'll just skip over the rows that had an updated column. i.e, the array for the above table is 1, 3, 5. Delete 5, 4 isn't in the array, so 3 is the last entry. Delete 3. 2 is not in the array, so the only entry is row 1.
The code would make the table end up like this:
| Header1 | Header2 | Header3 | Header4 | Update |
|---|---|---|---|---|
| First | row | value | data | |
| Second | row | value | data | YES |
| Fourth | row | value | data | YES |
With more data, such as 35 rows, and different YES placements, it may stop at 16 elements in the array, needing to delete row 18. However, it never truly deletes all the rows that it should.
Here's the code:
// Delete the rows without "YES" in the "Update" column
let dataRows = sheet.getRangeByIndexes(0, 0, sheet.getUsedRange().getRowCount(), 1); // Get all rows in column A
let dataValues = sheet.getRangeByIndexes(0, updateColumn, dataRows.getRowCount(), 1).getValues(); // Get "Update" column values
let nAry: number[] = [];
for (let rowIndex = 0; rowIndex < dataValues.length; rowIndex++) {
if (dataValues[rowIndex][0] !== "YES" && dataValues[rowIndex][0] !== "Update") {
nAry.push(sheet.getCell(rowIndex, updateColumn).getRowIndex()); //create 1D array of all rows requiring deletion
}
}
for(let i = 0; i < nAry.length; i++) { //loop through 1D array
let lastValue = nAry.pop(); //Put the last element from the array into a variable and remove from the array
sheet.getCell(lastValue, updateColumn).getEntireRow().delete(ExcelScript.DeleteShiftDirection.up); //use the last row number from the array, get the entire row and delete the row
}