[英]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. 换句话说,当在单元格A1中键入
00FF00
时,单元格B1的公式将其转换为#00FF00
,它会自动用相应的颜色突出显示单元格B1。 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
). 但是,一旦手动将单元格A1的十六进制值更改为另一种颜色(如
FF0000
,单元格B1就会自动将值更改为#FF0000
但不会自动更改为背景->保留了先前的背景(在这种情况下为#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() );
};
Note: 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). 这是一个有效的代码,但我需要手动输入十六进制值以使背景颜色自动显示->目前,B1中的十六进制值是由公式(其中包含A1 + A2 + A3单元格)得出的只能工作一次(然后,无论Hex值如何变化,即使单元格-B1中的Hex值发生变化,单元格B1仍保持其先前的背景色)。
// 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();
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.