Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-api

When using Sheets API to delete multiple rows and the endIndex is a row that doesn't exist in the sheet, how to handle it?


When pushing the rows to be deleted into an array, the last endIndex whose value is 809 is a row that is not in the sheet. How can I handle it in this case?

This is the piece of code building the request:

const sheetId = fabricDbSht.getSheetId();
let requests = [];
const fabricDbValues = fabricDbSht.getRange(1, 1, fabricDbSht.getLastRow(), fabricDbSht.getLastColumn()).getValues();
for (let a = fabricDbValues.length - 1; a >= 0; a--) {
  if (fabricDbValues[a][0] == systemId) {
    let row = a + 1;
    if (row > 0) {
      requests.push({
        deleteDimension: {
          range: {
            sheetId,
            startIndex: row,
            endIndex: row + 1,
            dimension: "ROWS"
          }
        }
      });
    }
  }
}
console.log('Requests: ' + JSON.stringify(requests))
Sheets.Spreadsheets.batchUpdate({requests}, fileId);

This is what the requests array looks like:

Requests: [{
  "deleteDimension": {
    "range": {
      "sheetId": 2032612900,
      "startIndex": 808,
      "endIndex": 809,
      "dimension": "ROWS"
    }
  }
}, {
  "deleteDimension": {
    "range": {
      "sheetId": 2032612900,
      "startIndex": 807,
      "endIndex": 808,
      "dimension": "ROWS"
    }
  }
}, {
  "deleteDimension": {
    "range": {
      "sheetId": 2032612900,
      "startIndex": 806,
      "endIndex": 807,
      "dimension": "ROWS"
    }
  }
}]

Solution

  • When I saw your script, I'm worried that you might misunderstand startIndex and endIndex. In this case, the 1st index is 0. So, how about the following modification?

    From:

    let row = a + 1;
    

    To:

    let row = a;