Search code examples
functiongoogle-apps-scriptdelete-row

Deleting Row - Google Apps Script "Cannot find method deleteRow((class))"


Here is my function:

function deleteContact(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var wsname = ss.getRangeByName("contactName").getValue();
  var wscl = ss.getSheetByName('Connection List');
  var wsRange = wscl.getRange("A1:A").getValues();

  for(var i = 0; i<wsRange.length;i++){
    if(wsRange[i][0] == wsname){ 
      var row = i+1; //This gets the row number 
    }
  var ui = SpreadsheetApp.getUi();
  var response = ui.alert("Are You Sure You Want To Delete " + wsname, ui.ButtonSet.YES_NO);

    if (response == ui.Button.YES) {
      var delr = wscl.deleteRow(row);
} 
  }
    }

I am able to get the row number, but once I click the 'YES' button, I am getting this error:

Cannot find method deleteRow((class)).

Any suggestions? I want the function to delete the row it found.


Solution

  • Try this:

    function deleteContact(){
      var ss=SpreadsheetApp.getActive();
      var wsname=ss.getRangeByName("contactName").getValue();
      var wscl=ss.getSheetByName('Connection List');
      var wsValues=wscl.getRange(1,1,wscl.getLastRow(),1).getValues();
      var d=0;
      for(var i=0;i<wsValues.length;i++){
        if(wsValues[i][0]==wsname){ 
          var row=i+1-d; //This gets the row number 
          var ui=SpreadsheetApp.getUi();
          var response=ui.alert("Are You Sure You Want To Delete " + wsname, ui.ButtonSet.YES_NO);
          if (response == ui.Button.YES) {
            wscl.deleteRow(row);
            d++;
          } 
        }
      }
    }
    

    As you delete the rows the ones that are left move up a row each time but the data was taken before the rows were deleted so the indices for calculating the address from the data array have to be compensated by the number of rows that have been deleted.

    You also had some lines that should have been within the scope of if(wsValues[i][0]==wsname){ and were not so I moved them in and now it only deletes lines with the correct name.