【问题标题】:Apps Script: createTextFinder - findAll(): instead changing the format of the whole cell, how the change the format of the found text onlyApps 脚本:createTextFinder - findAll():改为更改整个单元格的格式,如何仅更改找到的文本的格式
【发布时间】:2022-09-24 15:26:41
【问题描述】:

当找到 textToFind(在 C5:C23 范围内)时,以下函数会为整个单元格着色:

function findAndSetBackgroundColor(textToFind, format){


  //Find cells that contain \"ddd\"
  //let ranges = SpreadsheetApp.getActive()
  let ranges = SpreadsheetApp.getActive().getRange(\'C5:C23\')
    .createTextFinder(textToFind)
    .matchEntireCell(false)
    .matchCase(false)
    .matchFormulaText(false)
    .ignoreDiacritics(true)
    .findAll();

  //Set the background colors of those cells to yellow.
  ranges.forEach(function (range) {
      range.setTextStyle(format);
    });
}

想象一下我们在 C5:C23 范围内:

A header Another header
First thing row
Second thing row

由于matchEntireCell 设置为false,如果textToFindSecond,则整个单元格Second thing 将根据参数format 格式化

但我只想格式化找到的单词,而不是整个单元格。

怎么做?

    标签: google-apps-script google-sheets


    【解决方案1】:

    我相信你的目标如下。

    • textToFind 的文本包含在单元格“C5:C23”中时,您希望将文本样式设置为仅textToFind 的文本。

    在这种情况下,如何进行以下修改?我认为在这种情况下,当使用getRichTextValues()、搜索文本和setRichTextValues() 而不是TextFinder 时,脚本和过程可能很简单。

    修改后的脚本:

    function findAndSetBackgroundColor(textToFind, format) {
      const range = SpreadsheetApp.getActive().getRange('C5:C23');
      const v = range.getRichTextValues().map(r =>
        r.map(c => {
          const idx = c.getText().indexOf(textToFind);
          return idx != -1 ? c.copy().setTextStyle(idx, idx + textToFind.length, format).build() : c;
        })
      );
      range.setRichTextValues(v);
    }
    
    • 在此修改后的脚本中,例如,当使用textToFind = "sample"format = SpreadsheetApp.newTextStyle().setForegroundColor("red").build() 时,“C5:C23”的sample 的字体颜色更改为红色。

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多