简体   繁体   中英

Generate several colored background for one cell based on the input of different Hex value on a different cell?

In other words, when 00FF00 is typed in cell A1, cell B1's formula turns it into #00FF00 , which automatically highlights cell B1 with the corresponding color. The first time it works.

Yet, once cell A1's hexadecial value is manually changed to another color like FF0000 , cell B1 does automatically change the value to #FF0000 but not the background --> the previous background remains (in this case #00FF00 ).

Try the following script code:

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var c = ss.getActiveCell();
  if( s.getName() == 'Sheet1' && c.getA1Notation() == 'A1' )
  s.getRange('B1').setBackground( '#' + c.getValue() );
};


In the above code change the sheet name "Sheet1" and also cells "A1" & "B1" as per your requirement. 在上面的代码中,根据需要更改工作表名称“ Sheet1”以及单元格“ A1”和“ B1”。

Here is a code that works but I need to input the Hex values manually to get the background color to appear automatically --> for the moment, a hex value in B1 resulting from a formula (with A1+A2+A3 cells in it) will only work one time (then, what ever Hex value be changed, the cell B1 keeps its previous background color even though the Hex value in the cell -B1, changes).

// regex for hex color codes
HEX_COLOR_REGEX = /(^#[0-9A-Fa-f]{3}$)|(#[0-9A-Fa-f]{6}$)/;

// column to watch for changes (i.e. column where hex color codes are to be entered)
HEX_CODE_COLUMN = 5; // i.e. column A

// column to change when above column is edited
HEX_COLOR_COLUMN = 5; // i.e. column B

// utility function to test whether a given string qualifies as a hex color code
function hexTest(testCase) {
  return HEX_COLOR_REGEX.test(testCase);
}

function onEdit(e) {
  var range = e.range;
  var row = range.getRow();
  var column = range.getColumn();
  if (column === HEX_CODE_COLUMN) {
    var values = range.getValues();
    values.forEach( function checkCode(rowValue, index) {
      var code = rowValue[0];
      if (hexTest(code)) {
        var cell = SpreadsheetApp.getActiveSheet().getRange(row + index, HEX_COLOR_COLUMN);
        cell.setBackground(code);
        SpreadsheetApp.flush();
      }
    });
  }
}

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