4

我有一张有几千行和两列的工作表。我需要编写一个以行递增的脚本,并将其中一列中的值与同一列中的前 50 个值进行比较,看看它是否大于前 50 个条目的最大值。

我一直在尝试使用 Math.max(),但找不到正确的语法来让它在动态范围内工作。

4

4 回答 4

7

在电子表格中读取/写入时,始终尝试立即执行,避免循环单元格

我确信有更好的 javascript 方法,但是这段代码会让你在一列中获得最大值

function getMaxInColumn(column) {
  var column = 2; // just for testing
  var sheet = SpreadsheetApp.getActiveSheet();
  var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();

  var maxInColumn = colArray.sort(function(a,b){return b-a})[0][0];
  return maxInColumn;
}

问候,福斯托

于 2013-08-15T12:59:35.780 回答
5
var max = Math.max.apply(null, column.getValues());

但该列不能包含任何文本,只能包含数字和空值。否则,您需要从数组中排除文本。

于 2018-04-24T10:29:38.927 回答
2

您可以使用方法setFormula(formula)并使用类似=MAX(Range).

getDataRange()方法可能很有用。获得数据范围后,您可以确定最大行数getLastRow()和列getLastColumn()

于 2013-08-14T06:45:53.383 回答
0

为你的起点。编写后我没有针对任何东西运行我的代码,所以它可能需要一些调整。

var myss = assign spreadsheet by ID or name, etc
var mySheet = myss.getActiveSheet();
var col = 2;  //or whatever column you are working in
var startRow = 1;  //or whatever row you are going to start this on
var largeRow = startRow;  //Start with the first row as the "largest"

for ( var i = startRow; i <= mySheet.getLastRow(); i++){  //may need to change the "getLastRow()" check if columns aren't equal length
  var startCheck = i - 50;
  if (startCheck < startRow){  //The first 49 rows won't be able to check back 50 rows, you'll need to truncate to the starting row.
    startCheck = startRow;
  }
  largeRow = startCheck;
  for (j = startCheck; j < i; j++){  //cycle through the last 50 cells.
    if (mySheet.getRange(largeRow,col).getValue() < mySheet.getRange(j,col).getValue){  //start with the first of the 50 as the largest, update if a later one is larger
        largeRow = j;
    }
  }
  if (mySheet.getRange(i,col).getValue > mySheet.getRange(largeRow,col).getValue){  // Is the current value larger than the largest of the last 50.
        //Whatever you need to do if it is larger - your question didn't say.
  }
}
于 2013-08-14T19:35:53.817 回答