【问题标题】:Deleterow() within a For loop not deleting the right rows on GSheets在 For 循环中删除 Row() 不会删除表格上的正确行
【发布时间】:2020-05-13 03:49:38
【问题描述】:

不知道为什么这没有删除正确的行: 我已经尝试了所有可能的组合(在我的脑海中)。

function deleteItem() { 
  var sourceSheet = 'ArquivoItens';
  var destinationSheet = 'EditarItem';
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var source = ss.getSheetByName(sourceSheet);
  var LastRowSource = source.getLastRow();
  var LastColumnSource = source.getLastColumn();
  var values = source.getRange(2,1,LastRowSource,LastColumnSource).getValues();
  var csh = ss.getSheetByName(destinationSheet);
  var productCode = csh.getRange("W5").getValue();
  var productVersao = csh.getRange("AC4").getValue();

  for (var i = (values.length)-1; i > 0; i--) {
    if (values[i][0] == productCode && values[i][2] == productVersao) {
      Logger.log(values[i]);
      source.deleteRow(i);
      }
    }
}

请让我知道缺陷在哪里。欣赏!

【问题讨论】:

    标签: javascript for-loop google-apps-script google-sheets


    【解决方案1】:
    function deleteItem() { 
      var sourceSheet = 'ArquivoItens';
      var destinationSheet = 'EditarItem';
      var ss = SpreadsheetApp.getActiveSpreadsheet(); 
      var source = ss.getSheetByName(sourceSheet);
      var LastRowSource = source.getLastRow();
      var LastColumnSource = source.getLastColumn();
      //LastRowSource-startrow+1
      var values = source.getRange(2,1,LastRowSource-1,LastColumnSource).getValues();
      var csh = ss.getSheetByName(destinationSheet);
      var productCode = csh.getRange("W5").getValue();
      var productVersao = csh.getRange("AC4").getValue();
    
      for (var i = values.length-1; i >= 0; i--) {
        if (values[i][0] == productCode && values[i][2] == productVersao) {
          Logger.log(values[i]);
          source.deleteRow(i+2);//i+startrow which is two in this case
          }
        }
    }
    

    如果满足 productCode 和 productVersao 条件,这是要删除的行的屏幕截图。请参阅粗体列:

    【讨论】:

    • 这是删除上面的一行。我试过 i+1,但效果一样。
    • 我需要看一张你的床单的图片
    • 刚刚添加了他们的截图。
    • 您能否编辑您的答案以反映这一点,在 values.length 周围取消 ()? for (var i = values.length-1; i >= 0; i--) { if (values[i][0] == productCode && values[i][2] == productVersao) { source.deleteRow( i+2);这对我有用。你能解释一下怎么做吗?
    • 我总是查看 startRow 的数据。通常,您要删除的行很容易通过确定数据的 startRow 位置来确定。如果您取整个 dataRange() 则起始行为 1,如果 i=0 且起始行为 1,则您当前要删除的行必须为 i+1。但通常它几乎总是 i+起始行号。请记住,数组从零开始索引,行从一开始。但是,如果您的行的第一个范围是 2,那么当 i=0 时,该行必须是 2,因此 i+2。
    【解决方案2】:

    deleteRow 需要row 数字,而i 是数组的索引。数组索引从 0 开始,而行索引从 1 开始。

    source.deleteRow(i+1);
    

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2013-09-26
      • 2018-05-24
      相关资源
      最近更新 更多