Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created October 6, 2020 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/89aaa3adcd3a1fc37187ca61f389cbe9 to your computer and use it in GitHub Desktop.
Save tanaikech/89aaa3adcd3a1fc37187ca61f389cbe9 to your computer and use it in GitHub Desktop.
Setting Alternate Background Colors for Rows in Google Spreadsheet using Google Apps Script

Setting Alternate Background Colors for Rows in Google Spreadsheet using Google Apps Script

This is a sample script for setting alternate background colors for rows in Google Spreadsheet using Google Apps Script.

It has already been known when the conditional formatting rule and custom function are used, this can be simply achieved. Ref In this report, I would like to introduce the method for using Google Apps Script.

Sample script

In this sample script, the values of column "A" are checked.

function myFunction() {
  const colors = { color1: "#f4cccc", color2: "#d9ead3" };

  const sheet = SpreadsheetApp.getActiveSheet();
  const ranges = sheet
    .getRange("A1:A" + sheet.getLastRow())
    .getValues()
    .reduce(
      (o, [b], i) => {
        if (b != o.temp) {
          o.temp = b;
          o.c++;
        }
        o[["color1", "color2"][o.c % 2]].push(`${i + 1}:${i + 1}`);
        return o;
      },
      { color1: [], color2: [], c: 0, temp: "" }
    );
  Object.entries(colors).forEach(([k, v]) =>
    sheet.getRangeList(ranges[k]).setBackground(v)
  );
}
  • The process cost of this script can be reduced by using RangeList.

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment