Home > Net >  How to delete a row as indicated in a cell in google app script?
How to delete a row as indicated in a cell in google app script?

Time:11-06

What I want to do: I write a row number in a cell, let's say F1, and the value is 9. I want to add a button that calls a script that will delete the line as I wrote it into the cell, so in this example, line 9.

So I start with:

var s = SpreadsheetApp.getActive()
var sheet = s.getSheetByName('Books');
var row = sheet.getRange('F1');

However this:

sheet.deleteRow(row.getValue());

will give an out of bounds error. getDisplayValue does not work as well and putting it into an parseint doesn't work either.

The 9 hardcoded sheet.deleteRow(9); works of course.

I also debbuged and did a sheet.getRange('G1').setValue(row.getValue()); to verify that the 9 is indeed there, which it is, the 9 will be copied to cell G1.

sheet.getRange('A' row.getValue() ':J' row.getValue()).clearContent(); meanwhile will have it treat it as a A:J and delete every line not just one. Doing toString after getValue did also not change anything.

What am I missing here to turn the cell value into a range?

CodePudding user response:

Sheet.deleteRow(value of F1):

function onEdit(e) {
  const sh = e.range.getSheet();
  if(sh.getName() == "Your sheet name" && e.range.columnStart == 6 && e.range.rowStart == 1 && e.value) {
    sh.deleteRow(e.value)
  }
}

Cannot call this function from script editor must save in project and edit F1 of Your Sheet. You also need to edit line 3 and add the name of the appropriate sheet.

Using a checkbox for a button:

function onEdit(e) {
  e.source.toast("Entry")
  const sh = e.range.getSheet();
  if(sh.getName() == "Sheet0" && e.range.columnStart == 1 && e.range.rowStart == 1 && e.value == "TRUE") {
    e.source.toast("Gate1")
    e.range.setValue("FALSE")
    sh.deleteRow(sh.getRange("F1").getValue());
  }
}

Demo:

enter image description here

  • Related