![](/img/trans.png)
[英]Change cell value based on the cell's background color in Google Sheets
[英]Google Sheets - Set background color of cell based on text value automatically
是否可以根據單元格的文本值自動更改單元格的背景? 這些將用於任意數量的值,而不僅僅是預定義的。 這個想法是基於文本值生成一個“哈希”,然后基於該哈希,隨機選擇一種顏色。 不管是哪種顏色,只要不同的值有不同的顏色就可以輕松區分。
例如,假設單元格具有值:
它們都有不同的背景顏色,因為它們包含不同的文本值。 實際的背景顏色沒有區別。 理想情況下會有所不同的是,如果背景顏色為“暗”,則文本顏色為白色,如果背景顏色為“淺”,則文本顏色為黑色。 這樣您就可以隨時閱讀文本。
這是我對問題的近似:
const sS = SpreadsheetApp.getActiveSheet()
const docProperties = PropertiesService.getDocumentProperties()
function colorTheDifference() {
const { getRow, getNumRows, getColumn, getNumColumns } = sS.getDataRange()
const [rw, nRw, cl, nCl] = [getRow(), getNumRows(), getColumn(), getNumColumns()]
const values = sS.getRange(rw, cl, nRw, nCl).getValues()
for (let i = rw; i <= nRw; i++) {
for (let j = cl; j <= nCl; j++) {
const word = values[i - 1][j - 1]
if(!word) continue
sS.getRange(i, j).setBackground(saveColor(word))
}
}
}
function saveColor(word) {
if (docProperties.getKeys().includes(word)) {
return docProperties.getProperty(word)
} else {
const randomColorPick = randomColor()
docProperties.setProperty(word, randomColorPick)
return randomColorPick
}
}
// https://stackoverflow.com/a/5092846/14271633
const randomColor = () => '#' + (Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0');
function onOpen() {
// colorTheDifference()
SpreadsheetApp
.getUi()
.createMenu('Custom Menu')
.addItem('Color It', 'colorTheDifference')
.addToUi()
}
該腳本分析所有單元格值,將它們在DocumentProperties
中與隨機顏色相關聯(當樣本量增加時,這可能會導致某種問題,並且應實施控件以檢查這種顏色是否存在),然后將該顏色添加到單元格.
如您所見,我將它添加到菜單內的函數中,但可以在onOpen
內部調用它,以便在打開文檔時直接對其進行解析,或者將其與onEdit
關聯(我認為這將是矯枉過正)。
這不是近似問題的最佳方法,應該轉向batchUpdate
。
有趣的問題。
我寫了一些東西,它使用 onEdit() 函數根據特定列中的值來格式化/突出顯示/着色給定的行/范圍。
當我完成完整的文檔記錄后,我將在下面發表評論,但希望很容易弄清楚如何調整 userParams 對象。
在此樣本表上試一試。 B 列中的值將根據“圖例”的背景/字體顏色/文本樣式突出顯示該行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.