循环行,检查2个像元是否相等,然后更改像元值

时间:2019-05-14 16:43:36

标签: javascript google-apps-script

我想检查第2列的值是否为'foo',第28列的值是否为'bar',如果为true,则使第2列的值为'fizz'。

这是我到目前为止所拥有的。我以为我正确地检查了这些值,但也许我没有将其正确设置为起毛。

function functionName() {
   var sheet = SpreadsheetApp.getActive().getSheetByName('sheetname');

  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  for (var i = 2; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[2] == 'foo' && row[28] == 'bar'){
      row[2] == 'fizz';
    }
  }
}

1 个答案:

答案 0 :(得分:1)

如果foo和bar一起发嘶嘶声

function functionName() {
  var ss=SpreadsheetApp.getActive();//typically I find it more useful not to chain too much in the beginning so that you can reuse these assignments later.
  var sh=ss.getActiveSheet();
  var rg2=sh.getRange(2,2,sh.getLastRow()-1,1);//since you began your loop at two I assume you have a header so rows will be one less than getLastRow() to make up for the header
  var vA2=rg2.getValues();
  var rg28=sh.getRange(2,28,sh.getLastRow()-1,1);//You could use getDataRange but then you'd have to reload the whole sheet rather that just one column which could be a  problem if you have formulas in your sheet.
  var vA28=rg28.getValues();
  for(var i=0;i<vA2.length;i++) {
    if(vA2[i][0]=='foo' && vA28[i][0]=='bar')  {
      vA2[i][0]='fizz';
    }
  }
  rg2.setValues(vA2);//Dont forget this.  Its what actually loads the data into the spreadsheet.
}