如何用Google Apps Script对C列数值按指定规则逐行减1
Google Apps Script 指定列规则处理实现代码
你可以直接使用合并了复制+处理逻辑的函数,一次运行即可完成全部操作:
function copyAndProcessData() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Output'); // 复制B列内容到C列,仅保留值 sheet.getRange("B2:B").copyTo(sheet.getRange("C2:C"), {contentsOnly:true}); // 获取C列所有有效行数据 var lastRow = sheet.getLastRow(); var cRange = sheet.getRange("C1:C" + lastRow); var cValues = cRange.getValues(); // 从C3(数组索引为2)开始逐行处理 for (let i = 2; i < cValues.length; i++) { const current = cValues[i][0]; const prev = cValues[i-1][0]; // 跳过空值避免报错 if (!current) continue; // 匹配规则,符合跳过条件则不修改值 if (current > prev || current === 1) continue; // 其余情况设置为上一行值减1 cValues[i][0] = prev - 1; } // 处理结果写回C列覆盖原有数据 cRange.setValues(cValues); }
如果不需要每次都重新复制B列内容,也可以单独调用处理逻辑的函数:
function processColumnC() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Output'); var lastRow = sheet.getLastRow(); var cRange = sheet.getRange("C1:C" + lastRow); var cValues = cRange.getValues(); for (let i = 2; i < cValues.length; i++) { const current = cValues[i][0]; const prev = cValues[i-1][0]; if (!current) continue; if (current > prev || current === 1) continue; cValues[i][0] = prev - 1; } cRange.setValues(cValues); }
代码完全符合提出的三条处理规则,测试用示例数据的处理结果和预期完全一致,且保留C2原始值不修改,自动跳过空行不会报错。
内容的提问来源于stack exchange,提问作者Terje Flaten
相关产品推荐
相关产品推荐

