简体   繁体   中英

How to change/set background color of each individual cell in active range

I'm trying to change the background color of each individual cell but with some if statemnets. I have some code that does it for 1 cell, but I want it to do the same for all the active cells.

My google script code:

function changeColor(){
  // Change the background color
  let colorRed = '#f23a53';
  let colorOrange = '#f29f3a';
  let colorGreen = '#7de396';
  
  
  let actCell = SHEET.getActiveCell();
  let actData = actCell.getValue();
  
  if (Number.isInteger(actData)) {
    if (actData < 5) {
      actCell.setBackground(colorRed);
    } else if (actData < 9) {
      actCell.setBackground(colorOrange);
    } else if (actData == 9|| actData == 10) {
      actCell.setBackground(colorGreen);
    }
  } else {
    SHEET.getRange('D1').setValue(SpreadsheetApp.getActive().getActiveRange().getA1Notation()+" doesn't contain an integer.");
  }
}

Should I make a list of every active cell, then loop over it and run the function 'changeColor'?
Or is there a way to get the active range and look at every single cell at a time with a built in function?
Thx for your time.

To perform your request on an active range that contians more than one cell, use getActiveRange() instead of getActiveCell()

This will return you a 2-D range rather than a single cell.

Respecitively, you need to to loop through the cells of this range and verify either your conditions are fulfilled.

Useful is the method getCell() .

Sample modificaiton of your code:

function changeColor(){
  // Change the background color
  let colorRed = '#f23a53';
  let colorOrange = '#f29f3a';
  let colorGreen = '#7de396';
  
  let SHEET = SpreadsheetApp.getActive().getActiveSheet();
  let actRange = SHEET.getActiveRange();
  let actData = actRange.getValues();
  var startRow = actRange.getRow();
  var startColumn = actRange.getColumn();
  var integer = false;
  for(var i = 0; i < actData.length; i++){
    for(var j = 0; j < actData[0].length; j++){
      var actCell = actRange.getCell(1+i, 1+j);
      var value = actData[i][j];    
      if (Number.isInteger(value)) {
        integer = true;
        if (actData[i][j] < 5) {
          actCell.setBackground(colorRed);
        } else if (value < 9) {
          actCell.setBackground(colorOrange);
        } else if (value == 9|| value == 10) {
          actCell.setBackground(colorGreen);
        }
      }       
    }
  }
  if(integer == false) {
    SHEET.getRange('D1').setValue(SpreadsheetApp.getActive().getActiveRange().getA1Notation()+" doesn't contain an integer.");
  }
}

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