根据十六进制值设置单元格的背景颜色

yab*_*b86 3 google-sheets google-apps-script custom-function google-sheets-formula

我想根据另一个单元格中的十六进制值将背景颜色设置为一个单元格。到目前为止我所做的:

function setColorHEX(hex) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cell = ss.getActiveCell();
  cell.setBackground(hex);
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有人知道我做错了什么吗?

ow3*_*w3n 6

我试图做同样的事情并找到了这个脚本。它工作得很好,尽管我确实必须突出显示所有现有的单元格并将它们复制/粘贴回去才能使其工作。信用:https ://gist.github.com/wjmazza/131c050b88bb2a595d6049707693ec13

\n\n

在此输入图像描述

\n\n
/*\n\nThis script is meant to be used with a Google Sheets spreadsheet. When you edit a cell containing a\nvalid CSS hexadecimal colour code (like #000 or #000000), the background colour will be changed to\nthat colour and the font colour will be changed to the inverse colour for readability.\n\nTo use this script in a Google Sheets spreadsheet:\n1. go to Tools \xc2\xbb Script Editor \xc2\xbb Spreadsheet;\n2. erase everything in the text editor;\n3. change the title to "Set colour preview on edit";\n4. paste this code in;\n5. click File \xc2\xbb Save.\n*/\n\n/*********\n** Properties\n*********/\n/**\n * A regex pattern matching a valid CSS hex colour code.\n */\nvar colourPattern = /^#([0-9a-f]{3})([0-9a-f]{3})?$/i;\n\n\n/*********\n** Event handlers\n*********/\n/**\n * Sets the foreground or background color of a cell based on its value.\n * This assumes a valid CSS hexadecimal colour code like #FFF or #FFFFFF.\n */\nfunction onEdit(e){\n  // iterate over cell range  \n  var range = e.range;\n  var rowCount = range.getNumRows();\n  var colCount = range.getNumColumns();\n  for(var r = 1; r <= rowCount; r++) {\n    for(var c = 1; c <= colCount; c++) {\n      var cell = range.getCell(r, c);\n      var value = cell.getValue();\n\n      if(isValidHex(value)) {\n        cell.setBackground(value);\n        cell.setFontColor(getContrastYIQ(value));\n      }\n      else {\n        cell.setBackground(\'white\');\n        cell.setFontColor(\'black\');\n      }\n    }\n  }\n};\n\n\n/*********\n** Helpers\n*********/\n/**\n * Get whether a value is a valid hex colour code.\n */\nfunction isValidHex(hex) {\n  return colourPattern.test(hex);\n};\n\n/**\n * Change text color to white or black depending on YIQ contrast\n * https://24ways.org/2010/calculating-color-contrast/\n */\nfunction getContrastYIQ(hexcolor){\n    var r = parseInt(hexcolor.substr(1,2),16);\n    var g = parseInt(hexcolor.substr(3,2),16);\n    var b = parseInt(hexcolor.substr(5,2),16);\n    var yiq = ((r*299)+(g*587)+(b*114))/1000;\n    return (yiq >= 128) ? \'black\' : \'white\';\n}\n
Run Code Online (Sandbox Code Playgroud)\n