如何修改Google Sheets脚本:清除内容时保留N/A值
修改后的Google App Script脚本
以下是调整后的代码,实现查找I列文本"Check"并清除对应行J、K、L列内容,同时跳过值为N/A的单元格(包含文本"N/A"/"NA"和公式返回的#N/A错误值):
function ClearCells() { const sheetName = "Example"; // 设置工作表名称 const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); const searchText = "Check"; // 找到所有I列包含"Check"的单元格 const matchedCells = sheet .getRange("I3:I" + sheet.getLastRow()) .createTextFinder(searchText) .matchCase(true) .findAll(); // 遍历每个匹配的行 matchedCells.forEach(cell => { const row = cell.getRow(); // 遍历J、K、L列 ["J", "K", "L"].forEach(col => { const targetCell = sheet.getRange(col + row); const cellValue = targetCell.getValue(); // 判断是否为N/A:包含文本"N/A"、"NA",或公式返回#N/A错误 const isNA = cellValue === "N/A" || cellValue === "NA" || (cellValue instanceof Error && cellValue.message === "#N/A"); if (!isNA) { targetCell.clearContent(); } }); }); }
关键改动说明
- 取消批量范围清除逻辑,改为逐个单元格检查处理,确保精准跳过N/A值
- 添加N/A判断逻辑:覆盖文本形式的"N/A"/"NA",以及公式返回的#N/A错误值(若仅需处理文本形式,可删除错误值判断部分)
- 保留原文本匹配规则(区分大小写),仅调整清除操作的触发条件
内容的提问来源于stack exchange,提问作者Amaris Kunakorn
相关产品推荐
相关产品推荐

