google-sheetsgoogle-apps-script

Shade a specific tab if a value on that tab is equal to a value


Victim of my own inexperience here. I need a function that:

  1. Only runs on a sheet that I specify
  2. Runs whenever the sheet is opened
  3. Checks the value of a cell and shades that specific tab a color based on the value of the cell.

I've been reading posts since yesterday and have duct-taped this together from similar questions:

function onOpen(e) {
  const ss = SpreadsheetApp.getActive();
  ss.getSheets().forEach(sh => {
    if(sh.getRange("E2").isBlank()) {
      sh.setTabColor("#00ff00");//green
    } else {
      sh.setTabColor("#ff8000");//orange
    }
  });
}

It works but it's certainly doing things it doesn't need for my purposes, I just lack the experience to know how to modify some parts of it correctly.

  1. Can I change isBlank to search for a specific phrase? (isBlank works but I feel like a better-practice solution would be to have it key off a value).
  2. Can I set this to run on only one sheet that I specify (not sure how to modify the forEach argument).

Apologies for asking and huge thanks to anyone who can help. I'm sure this is a simple set of arguments, but I'm the farthest thing from a programmer.


Solution

  • Using onOpen() to check and shade a specific cell on a sheet

    It's possible to do what you'd like that will:

    • Only runs on a sheet that I specify
    • Runs whenever the sheet is opened
    • Checks the value of a cell and shades that specific tab a color based on the value of the cell

    Here is the code:

    function onOpen() {
      var ss = SpreadsheetApp.getActive();
      ss.getSheets().forEach(sh => {
        var sn = sh.getSheetName();
        var vl = sh.getRange("E2").getValue();
        if (sn == "Sheet1") {
          if (vl == "Test") {
            sh.setTabColor("green");
          } else {
            sh.setTabColor("orange");
          }
        }
      });
    }
    

    When the sheet is opened, the script checks Sheet 1's E2 cell if its value is Test and if it's true, sets the background to green. If not, it'll set it to orange.

    Here's another way to write the code:

    function onOpen() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sh = ss.getSheetByName("Sheet1");
      sh.getRange("E2").getValue() == "Test" ? sh.setTabColor("Green") : sh.setTabColor("Orange");
    }
    

    This uses getSheetByName() to get the sheet name and the shorthand version of if (Ternary Operator)


    Output

    If the text matches:

    Match

    If the text didn't match:

    mdm


    References: