首页 > 解决方案 > For 循环中的 Deleterow() 不会删除 GSheets 上的正确行

问题描述

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

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);
      }
    }
}

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

标签: javascriptfor-loopgoogle-apps-scriptgoogle-sheets

解决方案


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 条件,这是要删除的行的屏幕截图。请参阅粗体列: 在此处输入图像描述


推荐阅读