简体   繁体   中英

Need help finding the maximum value in a column in Google Sheets using Google Apps Script

I have a sheet with a couple of thousand rows and 2 columns. I need to write a script that will increment be row and compare the value in one of the columns to the previous 50 values in the same column and see if it is larger than the maximum value of the 50 previous entries.

I've been trying to use Math.max(), but can't find the correct syntax to use to get that to work on a dynamic range.

when reading / writing in spreadsheets always try to do it at once, avoiding looping over the cells

I am sure there is a better javascript approach but this code will get you the max value within a column

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

regards, Fausto

You can use the method setFormula(formula) and use a formula like =MAX(Range) .

The method getDataRange() might be useful. After you get the range of data you can determine the maximum number of rows getLastRow() and columns getLastColumn() .

var max = Math.max.apply(null, column.getValues());

But the column can't contain any text, only numbers and empty values. Or else you'll need to exclude text from your array.

starting point for you. I didn't run my code against anything after writing, so it may need some tweaking.

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.
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM