如何在Gsheets中的2张纸上删除同一行?

时间:2019-05-15 20:21:25

标签: javascript java google-apps-script

我有一个Gsheet,如果我需要删除Sheet1上包含文本“ none”的行,它也会删除Sheet2上的同一行(或行范围)。

我尝试了以下代码,该代码将删除Sheet1上的行,但是我无法获取它来删除Sheet2上的相应行

function sort() { 
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1')
              SpreadsheetApp.getActive().getSheetByName('Sheet2')
  var rows = sheet.getDataRange(); 
  var numRows = rows.getNumRows(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 

  for (var i = 0; i <= numRows - 1; i++) { 
    var row = values[i]; 
    if (row[9] == 'none') { 
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted); rowsDeleted++; 
    } 
  } 
}; 

预期结果是删除两张纸上的同一行,但目前仅在Sheet1上删除。

谢谢!

并且如果“无”文本位于Sheet1上与Sheet2的不同列中,我该怎么办?我试过了,但是似乎不起作用:

function sort() { 
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var sheet2 = SpreadsheetApp.getActive().getSheetByName('Sheet2');

  var rows = sheet1.getDataRange(); 
  var numRows = rows.getNumRows(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 

  for (var i = 0; i <= numRows - 1; i++) { 
    var row = values[i]; 
    if (row[9] == 'none') { 
      sheet1.deleteRow((parseInt(i)+1) - rowsDeleted);
    if (row[10] == 'none') {   
      sheet2.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++; 
    } 
  } 
};}

1 个答案:

答案 0 :(得分:0)

我将为两个单独的工作表创建两个单独的变量:

function sort() { 
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var sheet2 = SpreadsheetApp.getActive().getSheetByName('Sheet2');

  var rows = sheet1.getDataRange(); 
  var numRows = rows.getNumRows(); 
  var values = rows.getValues(); 
  var rowsDeleted = 0; 

  for (var i = 0; i <= numRows - 1; i++) { 
    var row = values[i]; 
    if (row[9] == 'none') { 
      sheet1.deleteRow((parseInt(i)+1) - rowsDeleted);
      sheet2.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++; 
    } 
  } 
};