You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets脚本开发需求:按条件添加单元格批注

Google Sheets 脚本:基于内容匹配自动添加批注

以下是实现你需求的完整脚本,能同时处理两类条件的批注添加:

function addConditionalNotes() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const dataRange = sheet.getDataRange();
  const values = dataRange.getValues();

  // 从第二行开始遍历(假设第一行是表头)
  for (let i = 1; i < values.length; i++) {
    const name = values[i][0]; // A列姓名
    const city = values[i][1]; // B列城市
    let noteContent = '';

    // 条件1:姓名包含对应城市(不区分大小写)
    if (name && city && name.toLowerCase().includes(city.toLowerCase())) {
      noteContent += 'Are you sure this is right?\n';
    }

    // 条件2:姓名包含连字符
    if (name && name.includes('-')) {
      noteContent += 'Hyphen in the name?\n';
    }

    // 设置或清除批注
    const targetCell = sheet.getRange(i + 1, 1);
    if (noteContent) {
      targetCell.setNote(noteContent.trim()); // 移除末尾多余换行
    } else {
      targetCell.clearNote(); // 不需要清除原有批注的话,删掉这行即可
    }
  }
}

关键细节说明

  • 匹配逻辑和你用的条件格式公式一致,采用不区分大小写的内容包含检查
  • 若同时满足两个条件,批注会换行显示两条提示内容
  • 脚本默认会清除不满足条件单元格的现有批注,如需保留原有批注,删除else { targetCell.clearNote(); }部分即可

使用步骤

  1. 打开目标Google Sheets文件,点击顶部菜单栏「扩展程序」→「Apps脚本」
  2. 替换默认代码为上述脚本,点击保存并给脚本命名
  3. 点击运行按钮,首次运行需完成权限授权,按提示操作即可
  4. 返回工作表,A列符合条件的单元格会自动添加上对应的批注

内容的提问来源于stack exchange,提问作者tsaria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 14:40:29