调整Google AppScript:排除指定列确定Google Sheet锁定范围的最后数据行
修改Google Apps Script以基于指定列确定锁定范围
核心修改思路
要实现仅通过1-16列判定最后数据行,需替换原脚本中sheet.getLastRow()的逻辑,改为仅遍历前16列的内容定位最后有数据的行,完全忽略17-18列的内容。
修改后的完整脚本
function lockSpecificRowsColumns() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getActiveSheet(); // --- 关键修改:仅基于1-16列计算最后数据行 --- const targetColumnsRange = sheet.getRange(1, 1, sheet.getMaxRows(), 16); // 选中1-16列所有行 const values = targetColumnsRange.getValues(); let lastDataRow = 0; // 从底部向上遍历,找到第一个有非空内容的行 for (let i = values.length - 1; i >= 0; i--) { if (values[i].some(cell => cell !== "" && cell !== null)) { lastDataRow = i + 1; // 转换为表格行号(数组索引从0开始) break; } } if (lastDataRow <= 5) { SpreadsheetApp.getUi().alert("1-16列中没有需要锁定的数据行(前5行除外)"); return; } // 获取工作表保护对象,无则创建 let protection = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE)[0]; if (!protection) { protection = sheet.protect().setDescription("锁定指定行和列"); } // 设置可编辑范围:前5行 + 17-18列(全范围) const editableRanges = [ sheet.getRange(1, 1, 5, sheet.getMaxColumns()), // 前5行所有列 sheet.getRange(1, 17, sheet.getMaxRows(), 2) // 17-18列所有行 ]; // 移除旧的可编辑范围,添加新范围 protection.getEditableRanges().forEach(range => protection.removeEditableRange(range)); editableRanges.forEach(range => protection.addEditableRange(range)); // 设置保护选项(可选,根据需求调整) protection.setWarningOnly(false); // false为强制锁定,true为仅警告 protection.addEditor(Session.getEffectiveUser()); // 保留当前用户编辑权限 }
关键代码解释
- 定位最后数据行:
- 通过
getRange(1, 1, sheet.getMaxRows(), 16)获取1-16列的完整范围 - 从表格底部向上遍历,找到第一个包含非空单元格的行,确保只基于目标列判定数据行边界
- 通过
- 可编辑范围配置:
- 保留前5行全列可编辑,同时保留17-18列所有行可编辑
- 自动移除旧的可编辑范围并替换为新配置,避免重复叠加
- 保护逻辑:
- 若不存在保护则自动创建,存在则更新配置
- 可通过
setWarningOnly切换强制锁定/仅警告模式
内容的提问来源于stack exchange,提问作者Essem
相关产品推荐
相关产品推荐

