我有一张有几千行和两列的表格。我需要编写一个脚本,该脚本将增加为行,并将其中一列中的值与同一列中的前50个值进行比较,并查看它是否大于前50个条目的最大值。
我一直在尝试使用Math.max(),但无法找到正确的语法来使其在动态范围内工作。
答案 0 :(得分:6)
在电子表格中进行读/写时,总是尝试立即进行,避免在单元格上循环
我确信有更好的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;
}
问候,Fausto
答案 1 :(得分:2)
您可以使用方法setFormula(formula)并使用类似=MAX(Range)
的公式。
方法getDataRange()可能很有用。获得数据范围后,您可以确定最大行数getLastRow()和列getLastColumn()。
答案 2 :(得分:1)
var max = Math.max.apply(null, column.getValues());
但该列不能包含任何文字,只包含数字和空值。否则,您需要从阵列中排除文本。
答案 3 :(得分: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.
}
}