How to delete row in Google Sheet if “Column A” cell CONTAINS given text

我怕爱的太早我们不能终老 提交于 2020-03-22 09:12:21

问题


I am trying to implement a Google Script so that if any cell in column A INCLUDES any specified text, then it will delete the entire row. Here is what i'm working with...

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName('Sheet1'); // change to your own
  var values = s.getDataRange().getValues();

  for (var row in values)
    if (values[row][0] == 'glass')
      s.deleteRow(parseInt(row)+1);

    else if (values[row][0] == 'Glass')
      s.deleteRow(parseInt(row)+1);

};

I am going to include multiple different criteria to clean my spreadsheet for me. Some of the rows might include "auto glass", "autoglass", "Glass repair", "Glass Doctor", "Glass Smith" Etc...

Currently, this code deletes the rows where the column A cell is "Glass" or "glass".

PLEASE HELP!!


回答1:


You must delete rows from the end. If you start at the beginning, and delete a row, all the rows below that row will now be out of sync with the order of the values in the array. After the first row is deleted, all the other rows that get deleted will probably be the wrong row, unless you adjusted the code for the row number. Try using this code:

function cleanRows() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Sheet1');

  var colA_Vals = sh.getRange(1, 1, sh.getLastRow(), 1).getValues();

  var i = 0,
      j = 0,
      thisVal,
      chkVal,
      arrayValsToChk = ['glass'];

  for (i=colA_Vals.length;i>0;i-=1) {
    thisVal = colA_Vals[i-1][0];
    //Logger.log('i: ' + i);

    for (j=0;j<arrayValsToChk.length;j+=1) {
      chkVal = arrayValsToChk[j].toLowerCase() //Change to all lower case;

      if (thisVal.indexOf(chkVal) !== -1) {
        ss.deleteRow(i);
      };
    };
  };
};

Note the array for all the values to check for. Add new values to the array to check for other values.




回答2:


Sandy is of course correct in how to delete rows. That is probably the most important point. I also suggest changing the strings to lower case so you just have to do one test. Try this:

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName('Sheet1'); // change to your own
  var values = s.getDataRange().getValues();
    for(var i=values.length;i>0;i-=1){
     var lcVal=values[i-1][0].toLowerCase() //Change to all lower case
     var index = lcVal.indexOf("glass"); //now you only have to check for  contains "glass"
     if (lcVal.indexOf("glass") > -1){
     s.deleteRow(i)};
  }}


来源:https://stackoverflow.com/questions/34643421/how-to-delete-row-in-google-sheet-if-column-a-cell-contains-given-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!