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

Google Sheets中如何根据其他单元格颜色动态设置单元格背景色?

在Google Sheets中实现基于其他单元格背景色的条件格式

完全可行,但原生条件格式不支持检测单元格背景色作为触发条件,需要借助Google Apps Script来实现,具体步骤如下:

实现步骤

  1. 打开目标Google Sheets文档,点击顶部菜单栏的「扩展程序」→「Apps Script」,进入脚本编辑器。
  2. 删除编辑器里的默认代码,粘贴以下自定义脚本:
function onEdit(e) {
  const sheet = e.source.getActiveSheet();
  const range = e.range;
  
  // 仅监听A列的操作(包括背景色修改)
  if (range.getColumn() === 1) {
    const row = range.getRow();
    const aCell = sheet.getRange(row, 1);
    const cCell = sheet.getRange(row, 3);
    
    // 替换成你实际使用的绿色十六进制色值(比如#00ff00)
    const targetGreen = "#00ff00";
    const aColor = aCell.getBackground();
    
    if (aColor === targetGreen) {
      // A列单元格为绿色时,C列对应单元格设为透明
      cCell.setBackground(null);
    } else {
      // 按原规则设置C列背景色
      const cValue = cCell.getValue();
      const today = new Date();
      // 去除时间部分,只比较日期
      const cDate = new Date(cValue);
      const todayDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      const cDateOnly = new Date(cDate.getFullYear(), cDate.getMonth(), cDate.getDate());
      
      if (cDateOnly.getTime() === todayDate.getTime()) {
        cCell.setBackground("#ffff00"); // 黄色
      } else if (cDateOnly < todayDate) {
        cCell.setBackground("#ff0000"); // 红色
      } else {
        cCell.setBackground(null); // 未到日期则透明
      }
    }
  }
}
  1. 点击编辑器顶部的保存按钮,给脚本起一个易记的名称(比如「OrderDeliveryFormat」)。
  2. 返回表格测试:
    • 把A1的背景设为目标绿色,C1会自动变为透明;
    • 把A1的背景改成其他颜色,C1会根据日期和今天的对比,自动切换黄色/红色/透明。

注意事项

  • 脚本中的targetGreen值必须和你实际使用的绿色完全匹配,你可以通过点击A列单元格的背景色选择器,查看并复制对应的十六进制代码替换进去;
  • 脚本通过onEdit触发,只要修改A列的内容或背景色,就会自动更新对应C列的格式;
  • 如果要批量处理已有数据,可以添加以下批量处理函数,点击编辑器的运行按钮执行一次即可:
function batchUpdateAllRows() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  const lastRow = sheet.getLastRow();
  const targetGreen = "#00ff00"; // 同样替换成你的目标绿色值
  
  for (let row = 1; row <= lastRow; row++) {
    const aCell = sheet.getRange(row, 1);
    const cCell = sheet.getRange(row, 3);
    const aColor = aCell.getBackground();
    
    if (aColor === targetGreen) {
      cCell.setBackground(null);
    } else {
      const cValue = cCell.getValue();
      const today = new Date();
      const cDate = new Date(cValue);
      const todayDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      const cDateOnly = new Date(cDate.getFullYear(), cDate.getMonth(), cDate.getDate());
      
      if (cDateOnly.getTime() === todayDate.getTime()) {
        cCell.setBackground("#ffff00");
      } else if (cDateOnly < todayDate) {
        cCell.setBackground("#ff0000");
      } else {
        cCell.setBackground(null);
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:05:58