Google Apps Script如何遍历电子表格所有已使用列批量设置单元格背景色
修复后可遍历所有已使用列的代码
function insertColor2() { const sheetName = "結果1"; // 可自行修改为对应工作表名称 // 1. 获取工作表全量数据 const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheetByName(sheetName); const lastCol = sheet.getLastColumn(); // 动态获取当前工作表最后一个已使用的列索引 const startCol = 7; // G列对应索引为7,作为处理的起始列 const processColCount = lastCol - startCol + 1; // 计算需要处理的总列数 const allValues = sheet.getRange(3, startCol, sheet.getLastRow() - 2, processColCount).getValues(); // 一次性取出所有需要处理列的第3行及以下数据 // 2. 逐列计算背景色规则 for (let colIndex = 0; colIndex < processColCount; colIndex++) { // 提取当前列的所有值,匹配原有入参结构 const currentColValues = allValues.map(row => row[colIndex]); const values = [currentColValues]; // 完全保留原有的颜色计算逻辑,不改动业务规则 const backgroundColors = values.map(([,,c,,,...g]) => g.reduce((o, e) => { if (e.toString() != "") { o.total += e; o.colors.push(c >= o.total ? null : "red"); } else { o.colors.push(null); } return o; }, {colors: [], total: 0}).colors ); const flatten = [].concat.apply([], backgroundColors); const newArr = []; while(flatten.length) newArr.push(flatten.splice(0,1)); // 3. 写入当前列的背景色设置 sheet.getRange(8, startCol + colIndex, newArr.length, 1).setBackgrounds(newArr); } }
关键修改说明
- 新增动态获取最后使用列的逻辑,后续表格新增列后不需要调整代码也能自动覆盖所有已使用列
- 原有颜色判断规则完全保留,不会影响原本的业务逻辑效果
- 采用逐列循环处理的方式,和原单列逻辑完全对齐,避免批量处理出现规则偏差
内容的提问来源于stack exchange,提问作者Timonek
相关产品推荐
相关产品推荐

