Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

javascript - How to change color of a cell if the previous cell contains the hex color name?

On google sheets I have a single column dataset where each cell contains hex color names (i.e. #eac285)

how can I programmatically set the background color of the corresponding cells in the next column to those colors?

Can I do this in the format "=function(x)"

question from:https://stackoverflow.com/questions/65944323/how-to-change-color-of-a-cell-if-the-previous-cell-contains-the-hex-color-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Explanation:

The idea is to get the values of the column which contains the hex colors and then use setBackgrounds on the column right next to it to set the background colors.

  • You can't use this solution as a custom function (custom formula in the sheet), because custom functions don't allow for methods that require permission such us setting values to the sheet. More details regarding this restriction in the official documentation.

  • You can run the following script (with adjustments based on your scenario) from the script editor and/or create a custom menu to execute it from there if you want a more user friendly way to do that.

Code snippet:

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sh = ss.getSheetByName("Sheet1");
  const hex_colors = sh.getRange('A1:A'+sh.getLastRow()).getValues();
  sh.getRange('B1:B'+sh.getLastRow()).setBackgrounds(hex_colors);
}

Example sheet used for code snippet:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...