Home > database >  How to return a list of sheet names based on the value within a certain cell of each sheet in Google
How to return a list of sheet names based on the value within a certain cell of each sheet in Google

Time:01-19

I am trying to return a list of sheet names based on whether a particular cell value meets the conditions of an if statement. When I try to run the script in Google Sheets, I receive a #REF error (Reference does not exist).

Here is the code I have:

function priceIncrease(number) { 
  var out = new Array();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var price = ss.getRange("H4").getValue();
  var sheets = ss.getSheets();
  for (var i=8 ; i<sheets.length ; i  ) 
    if (price[i] < number) {
      out.push([sheets[i].getName()])
      };
  return out; 
}

I want the priceIncrease() function to return a list of client names (the client names are the same as the sheet names) whose value in cell H4 is less than the value of the number I input into the function. For example, if I put in priceIncrease(-20), I want the script to return a list of sheet names whose H4 cell is less than -20.

CodePudding user response:

You need to get the value in cell H4 separately on each sheet, like this:

function priceIncrease(number) {
  if (typeof number !== 'number') {
    throw new Error(`priceIncrease() expected a number but got "${number}" instead.`);
  }
  const result = [];
  SpreadsheetApp.getActive().getSheets().forEach(sheet => {
    const price = sheet.getRange('H4').getValue();
    if (price < number) {
      result.push([sheet.getName()]);
    };
  });
  return result.length ? result : null;
}
  • Related