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

如何编写脚本实现单元格背景色改为#ff0000时弹出验证提醒?

实现方案(Google Sheets 应用脚本)

以下方案通过可安装触发器监听单元格格式修改动作,仅当本次操作将监控范围内的单元格改为指定红色时才触发提醒,不会误触发原有红色单元格的其他操作。

部署步骤

1. 粘贴脚本代码

打开目标表格,点击顶部菜单「扩展程序」->「Apps 脚本」进入脚本编辑器,替换默认内容为以下代码:

function onBackgroundChange(e) {
  // 可自定义配置项
  const MONITOR_RANGE = "RW6:TR36";
  const TRIGGER_COLOR = "#ff0000";
  const REMIND_CONTENT = "请记得发起/核查对应问题的相关整改动作";

  // 仅处理格式修改类事件
  if (e.changeType !== "FORMAT") return;

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const editRange = sheet.getActiveRange();
  const monitorRange = sheet.getRange(MONITOR_RANGE);

  // 校验修改区域是否在监控范围内
  const rangeMatched = (
    editRange.getRow() >= monitorRange.getRow() &&
    editRange.getLastRow() <= monitorRange.getLastRow() &&
    editRange.getColumn() >= monitorRange.getColumn() &&
    editRange.getLastColumn() <= monitorRange.getLastColumn()
  );
  if (!rangeMatched) return;

  const newBackgrounds = editRange.getBackgrounds();
  let needRemind = false;

  // 遍历对比新旧背景色,仅识别新改为红色的单元格
  for (let row = 0; row < newBackgrounds.length; row++) {
    for (let col = 0; col < newBackgrounds[row].length; col++) {
      const currentColor = newBackgrounds[row][col].toUpperCase();
      const cell = editRange.getCell(row + 1, col + 1);
      // 用单元格备注存储上一次背景色做对比,不影响单元格内容
      const prevColor = cell.getNote().trim().toUpperCase();
      
      if (currentColor === TRIGGER_COLOR.toUpperCase() && prevColor !== TRIGGER_COLOR.toUpperCase()) {
        needRemind = true;
      }
      // 更新备注为最新背景色
      cell.setNote(newBackgrounds[row][col]);
    }
  }

  if (needRemind) {
    SpreadsheetApp.getUi().alert(REMIND_CONTENT);
  }
}

2. 配置触发器

  • 点击脚本编辑器左侧菜单栏「触发器」选项,点击右下角「添加触发器」
  • 按以下参数配置触发器:
    • 选择要运行的函数:onBackgroundChange
    • 选择事件来源:电子表格
    • 选择事件类型:变更
  • 保存后按提示完成账号授权即可生效

说明

  • 如果你使用的是Excel/WPS表格,可以用VBA实现相同逻辑,核心是监听Worksheet_Change事件判断背景色变更即可
  • 代码里的监控范围、触发颜色、提醒内容都可以根据实际需求自行修改

内容的提问来源于stack exchange,提问作者Sam.Palf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:06:06