[英]Apps Script Gsheets - Paste same value in different cells - efficient solution
[英]Color cells with same value in different columns (different rows) in app script
我想为不同列中具有相同值的单元格着色。 有没有办法在应用脚本中做到这一点?
请自行定义distinctColors
并确保有足够的 colors 用于您的数据。
function test() {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getDataRange();
const values = range.getValues();
const rows = values.length;
const cols = values[0].length;
const colors = new Array(rows).fill().map(row => new Array(cols));
const distinctColors = ['red', 'blue', 'green', 'yellow'];
const distinctValues = {};
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const value = values[i][j];
if (!distinctValues[value]) { distinctValues[value] = []; }
distinctValues[value].push({i: i, j:j});
}
}
let k = 0;
for (const array of Object.values(distinctValues)) {
if (array.length == 1) { continue; }
for (const v of array) {
colors[v.i][v.j] = distinctColors[k];
}
k++;
}
range.setBackgrounds(colors);
}
const colorSameValues = () => {
const sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1'),
range = sheet.getDataRange(),
values = range.getValues(),
set /* unique set */ = new Set(values.flat()),
map /* values to color map */ = new Map(),
hex /* random hex color code */ = () =>
'#' +
Array(3)
.fill()
.map(() =>
Math.floor(Math.random() * 256)
.toString(16)
.padStart(2, '0')
)
.join('');
set.delete('');
set.forEach((val) => map.set(val, hex()));
range.setBackgrounds(values.map((row) => row.map(map.get.bind(map))));
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.