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

修改Google Apps Script实现预定义单元格范围特定字符自动变色

修改Google Apps Script实现预定义范围自动着色

修改后的完整代码

function run() {
  // 预定义目标范围:替换为你的工作表名称和目标单元格范围
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("你的工作表名称");
  const targetRange = sheet.getRange("B2:B100");
  
  // 自定义需要标记为红色的字符/字符串
  const targetTexts = ["|", "hello"];
  
  const values = targetRange.getDisplayValues();
  const richTextValues = values.map(row => {
    return row.map(cell => {
      let richText = SpreadsheetApp.newRichTextValue().setText(cell);
      targetTexts.forEach(text => {
        let startIndex = 0;
        while (startIndex < cell.length) {
          startIndex = cell.indexOf(text, startIndex);
          if (startIndex === -1) break;
          const endIndex = startIndex + text.length;
          richText = richText.setTextStyle(startIndex, endIndex, 
            SpreadsheetApp.newTextStyle().setForegroundColor("#ff0000").build());
          startIndex = endIndex;
        }
      });
      return richText.build();
    });
  });
  
  targetRange.setRichTextValues(richTextValues);
}

关键修改说明

  • 移除了依赖手动选中单元格的逻辑,直接在代码中通过getSheetByName()和getRange()预定义需要处理的范围,记得把"你的工作表名称"替换成你实际使用的工作表名称
  • 保留了原有的多字符着色逻辑,你可以通过修改targetTexts数组来添加或调整需要标记为红色的内容(支持单个字符或完整字符串)
  • 现在直接点击脚本的运行按钮即可执行,无需提前手动选中单元格范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:01:09