简体   繁体   中英

Color range of cells based on values in different sheet

I have 13 sheets in Google Sheets, 12 sheets having names in row and dates in column header.

I want the whole column to be grey-formatted based on holidays listed in a "HolidayList" sheet. I have written some code, which is not working at the proper cell address:

function formatForHoliday() {
  Logger.clear();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var holidays = ss.getRange("HolidayList!A2:A80").getValues();
  // Logger.log(holidays);

  // For each sheet
  for ( var s = 0; s <= 12; s++ ) {
    var sheet = ss.getSheets()[s];
    // Logger.log(sheet);
    var values = sheet.getRange(sheet.getName() + "!F3:NF3").getValues();
    // var newValues = [];
    // Logger.log(values);

    // In each sheet, for each value
    for (i in values[0]) {
      for (j in holidays) {
        var val = values[0][i];
        var hol = holidays[j][0];
        Logger.log(val.valueOf());
        Logger.log(hol.valueOf());

        if (val.valueOf() == hol.valueOf()) {
          // newValues.push(values[0][i]);
          var cellsRange = sheet.getRange(4, i + 6, 52, 1);
          var address = cellsRange.getA1Notation();
          cellsRange.setBackground('grey');
        }
      }
    }
  }
}

Your code seems to be fine, the only issue I can see right now is that you're fetching range of set[multiple] of cells but setting background to only one.

And you're applying setBackground() to a string. getA1Notation() returns string not range. https://developers.google.com/apps-script/reference/spreadsheet/range#geta1notation

setBackground() can be applied to range only.

https://developers.google.com/apps-script/reference/spreadsheet/range#setbackgroundcolor

var cellsRange = sheet.getRange(4, i + 6, 52, 1);
var address = cellsRange.getA1Notation();
cellsRange.setBackground('grey');

Rather you should set to all of those cells whose range/address you have fetched. https://developers.google.com/apps-script/reference/spreadsheet/range#setbackgroundscolor

I think what you should do is that :

  1. You're doing step one ie fetching range correctly.

var cellsRange = sheet.getRange(4, i + 6, 52, 1);

  1. Now you should make an array of same dimension as of (4, i + 6, 52, 1) ie I think [48X1]

  2. Fill all it's element with 'grey'

  3. Use setBackgrounds() method. https://developers.google.com/apps-script/reference/spreadsheet/range#setbackgroundscolor

Let me know if this resolves your issue. Or if you have any further doubts/suggestions.

Thanks

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