在单元格中写下,然后在相邻单元格中出现我写下的HEX颜色
这不能用公式来完成,但可以用
onEdit(e)
脚本,如下所示:
'use strict';
/**
* Simple trigger that runs each time the user manually edits the spreadsheet.
*
* @param {Object} e The onEdit() event object.
*/
function onEdit(e) {
if (!e) {
throw new Error('Please do not run the onEdit(e) function in the script editor window.');
}
setHexColorInNextCell_(e);
}
/**
* Changes the backgroup color of a cell when a hex color code is entered in the cell to its left.
*
* @param {Object} e The onEdit() event object.
*/
function setHexColorInNextCell_(e) {
// version 1.0, written by --Hyde, 21 July 2024
// - see https://stackoverflow.com/q/78773946/13045193
try {
const parameters = [
////////////////////////////////
// [START modifiable parameters]
{
sheetsToWatch: /./i,
sheetsToExclude: /^(Master)$/i,
patternsToWatch: [/#[a-f\d]{6}/i], // hex color codes are like #00ff00
},
// [END modifiable parameters]
////////////////////////////////
];
const value = e.value || e.range.getDisplayValue();
if (!value) return;
let sheet, sheetName;
const settings = parameters.find(p =>
(!p.patternsToWatch.length || p.patternsToWatch.some(p => value.match(p)))
&& (sheetName = sheetName || (sheet = sheet || e.range.getSheet()).getName()).match(p.sheetsToWatch)
&& (!p.sheetsToExclude || !sheetName.match(p.sheetsToExclude))
);
if (!settings) return;
const nextCell = e.range.offset(0, 1);
nextCell.setBackground(value);
} catch (error) {
e.source.toast(`${error.message} ${error.stack}`, 'Error in setHexColorInNextCell_()', 30);
throw error;
}
}
我的谷歌工作表中已经有了onEdit功能
重命名当前
onEdit()
功能类似
anotherOnEdit()
并将其添加到
on编辑(e)
上面的函数,如下所示:
// ...
setHexColorInNextCell_(e);
anotherOnEdit(e);
}
当您输入十六进制颜色代码时,该脚本将自动运行,例如
#ff0000
在一个牢房里。
请参阅
Simple triggers
和
onEdit(e) best practices
.