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

如何在Google Sheets中实现单元格内指定文本的局部批量加粗

Google Sheets实现单元格内指定短语局部加粗方案

你可以通过Google Apps Script实现和上述VBA完全一致的效果,操作和代码如下:

  • 打开目标Google Sheets表格,点击顶部菜单栏「扩展程序」→「Apps 脚本」,进入脚本编辑页面
  • 删除编辑区默认的空白代码,粘贴下方完整脚本代码
  • 点击页面顶部的保存按钮,给项目自定义命名(如「局部加粗工具」),完成后关闭脚本编辑页
  • 刷新表格页面,顶部菜单栏会新增「自定义工具」菜单,即可使用功能
// 自定义菜单生成
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('自定义工具')
    .addItem('选中区域指定短语加粗', 'findAndBold')
    .addToUi();
}

// 核心加粗逻辑
function findAndBold() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const ui = SpreadsheetApp.getUi();
  let matchCount = 0;

  // 确认待处理文本范围
  const defaultRange = sheet.getActiveRange().getA1Notation();
  const dataRangeRes = ui.prompt('请输入要处理的文本数据范围(例如B1:B100),默认使用当前选中范围:', defaultRange, ui.ButtonSet.OK_CANCEL);
  if (dataRangeRes.getSelectedButton() !== ui.Button.OK) return;
  const dataRange = sheet.getRange(dataRangeRes.getResponseText());
  const cellValues = dataRange.getValues();
  const originStyles = dataRange.getTextStyles();

  // 确认关键词范围
  const keywordRangeRes = ui.prompt('请输入存放待加粗关键词的范围(例如A1:A50):', ui.ButtonSet.OK_CANCEL);
  if (keywordRangeRes.getSelectedButton() !== ui.Button.OK) return;
  const keywordRange = sheet.getRange(keywordRangeRes.getResponseText());
  const keywordList = keywordRange.getValues()
    .flat()
    .filter(item => item.toString().trim() !== '')
    .map(item => item.toString().trim());

  if (keywordList.length === 0) {
    ui.alert('关键词范围内无有效内容');
    return;
  }

  // 遍历单元格处理格式
  for (let rowIdx = 0; rowIdx < cellValues.length; rowIdx++) {
    for (let colIdx = 0; colIdx < cellValues[rowIdx].length; colIdx++) {
      const cellText = cellValues[rowIdx][colIdx].toString();
      if (cellText === '') continue;

      const richTextBuilder = SpreadsheetApp.newRichTextValue().setText(cellText);
      richTextBuilder.setTextStyle(originStyles[rowIdx][colIdx]); // 保留单元格原有格式

      keywordList.forEach(keyword => {
        const keywordLength = keyword.length;
        let startIndex = cellText.indexOf(keyword);
        while (startIndex !== -1) {
          const boldStyle = SpreadsheetApp.newTextStyle().setBold(true).build();
          richTextBuilder.setTextStyle(startIndex, startIndex + keywordLength, boldStyle);
          matchCount++;
          startIndex = cellText.indexOf(keyword, startIndex + keywordLength);
        }
      });

      dataRange.getCell(rowIdx + 1, colIdx + 1).setRichTextValue(richTextBuilder.build());
    }
  }

  // 输出处理结果
  if (matchCount > 0) {
    ui.alert(`处理完成,共加粗了${matchCount}处匹配文本`);
  } else {
    ui.alert('未找到任何匹配的指定文本');
  }
}

如果你需要不区分大小写匹配关键词,只需要把代码中let startIndex = cellText.indexOf(keyword);修改为let startIndex = cellText.toLowerCase().indexOf(keyword.toLowerCase());即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:06:03