简体   繁体   中英

Delete Row in Google Sheets Based on Cell Text (if contains)

I am trying to create a script that will automatically delete the row if the cell contains, but does not exactly match, the condition. For example, the script would delete the rows if the cell contains gmail.com, as part of a larger email

123@gmail.com
123@yahoo.com
456@gmail.com
456@yahoo.com

The two yahoo emails would be saved because they do not meet the condition. However, I am unsure of the proper conditional dictation to use when writing my script. Here is what I have so far.

function deleteRows() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName('Sheet1');
  var r = s.getRange('B:B');
  var v = r.getValues();
  for(var i=v.length-1;i>=0;i--)
    if(v[0,i] 'gmail.com')
      s.deleteRow(i+1);
};

I would put a ==, but this will only delete rows that match exactly with gmail.com. What would I use in place of the == to make it essentially a text contains condition?

Try this:

function deleteMatchingRows(string) {
  var string=string||'gmail.com';
  var ss = SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet1');
  var lngth=sh.getLastRow();
  var rg=sh.getRange(1,2,lngth,1);
  var vA=rg.getValues();
  var n=0;  
  for(var i=1;i<vA.length;i++){
    if(vA[i][0] && vA[i][0].indexOf(string)>-1){
      sh.deleteRow(i-n+1);
      n++;
    }    
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM