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

如何在Google Sheet中搜索指定词语并高亮包含匹配内容的行

问题原因

SpreadsheetApp中的getRange()方法不支持接收{row: 行号, col: 列号}格式的对象数组作为入参。同时你调用createTextFinder().findAll()返回的本身就是匹配到的Range对象数组,无需额外转换坐标。


方案1:直接遍历设置(适合中小数据量)

你可以直接遍历匹配得到的Range数组设置背景,还可以自行选择是给匹配单元格上色,还是给匹配单元格所在整行上色:

function highlightMatchWords() {
  // 所有要查找的关键词统一放在数组里,后续加词直接修改这个数组即可
  const targetWords = ["FIRST WORD", "SECOND WORD"];
  const sheet = SpreadsheetApp.openById('23PzZzz23442321212i1rJDnasXD').getSheetByName('sheetname');
  const lastCol = sheet.getLastColumn(); // 给整行上色时会用到

  targetWords.forEach(word => {
    const matchRanges = sheet.createTextFinder(word).findAll();
    matchRanges.forEach(range => {
      // 选项1:仅给匹配到的单元格设置黄色背景
      range.setBackground('yellow');
      // 选项2:给匹配单元格所在整行设置背景,需要时注释上一行、打开下面这行即可
      // sheet.getRange(range.getRow(), 1, 1, lastCol).setBackground('yellow');
    })
  })
}

方案2:批量操作(适合大数据量,性能更高)

如果匹配结果很多,为了减少API调用次数提升效率,可以把所有匹配区域的A1标识收集起来,用getRangeList批量设置背景:

function highlightMatchWordsBatch() {
  const targetWords = ["FIRST WORD", "SECOND WORD"];
  const sheet = SpreadsheetApp.openById('23PzZzz23442321212i1rJDnasXD').getSheetByName('sheetname');
  const matchA1List = [];

  targetWords.forEach(word => {
    const matchRanges = sheet.createTextFinder(word).findAll();
    matchRanges.forEach(range => {
      // 选项1:收集匹配单元格的A1标识
      matchA1List.push(range.getA1Notation());
      // 选项2:收集整行的A1标识,需要时注释上一行、打开下面这行即可
      // matchA1List.push(`${range.getRow()}:${range.getRow()}`);
    })
  })

  if (matchA1List.length) {
    sheet.getRangeList(matchA1List).setBackground('yellow');
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:57:00