Google Spreadsheet conditional formatting script

后端 未结 4 853
遥遥无期
遥遥无期 2020-12-16 13:22

I am trying to figure out how to use conditional formatting on a google spreadsheet similar to what you can do in excel via a formula.

I want cell A2 to change to Gr

4条回答
  •  独厮守ぢ
    2020-12-16 13:37

    With the latest Sheet API you can programmatically add a conditional formatting rule to your sheet to do the highlighting.

    You can add a custom formula rule that will set the background colour to green in column A where column O is "X" like this:

    function applyConditionalFormatting() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
    
      var numRows = sheet.getLastRow();
      var rangeToHighlight = sheet.getRange("A2:A" + numRows);
      var rule = SpreadsheetApp.newConditionalFormatRule()
          .whenFormulaSatisfied('=INDIRECT("R[0]C[14]", FALSE)="X"')
          .setBackground("green")
          .setRanges([rangeToHighlight])
          .build();
    
      var rules = sheet.getConditionalFormatRules();
      rules.push(rule);
      sheet.setConditionalFormatRules(rules);
    }
    

    The range that the conditional formatting applies to is the A column from row 2 to the last row in the sheet.

    The custom formula is:

    =INDIRECT("R[0]C[14]", FALSE)="X"
    

    which means go 14 columns to the right of the selected range column and check if its value is "X".

    Column O is 14 columns to the right of column A.

提交回复
热议问题