Coloring the searched word in Google Sheets

How do I color all the words in the results that contain the text I searched for with the query function?

In Google Sheets, I use the “query function” to search the column C in Sheet1 for the text in cell B2, how can I use Google Apps scripts to color all the words in the results that contain the text I searched for?
And if I change the text in B2, a result of the query will change and the apps script will re-color the new words in the results that contain the new text.

This is a link to a sample spreadsheet that explains what I need:

Sample spreadsheet

This picture explains what I want to do:

Modification points:

  • From your showing image, I noticed that in your situation, the values of column “C” is put using a formula like =QUERY(Sheet1!A2:C,"where C contains '"&B1&"'"). In this case, when the text style in the column “C” is changed by a script and the manual operation, an error occurs because the values put by a formula cannot be overwritten. In your showing the expected result, I think that the column “G” is put without the formula. By this, the text style can be changed.

In order to avoid this issue, I would like to propose the following workaround. The steps of this workaround are as follows.

  1. Put a search text like rare into cell “B1” of “Search” sheet.
  2. Clear cells “A4:C”.
  3. Put your formula =QUERY(Sheet1!A2:C,"where C contains '"&B1&"'") in to cell “A4”.
  4. Convert the formula to text.
  5. Set text style using the search text to column “C”.

By these steps, when you put a search text, the text styles of column “C” can be changed.

When this workaround is reflected in a sample script, it becomes as follows.

Sample script:

function onEdit(e) {
  const { range } = e;
  const sheet = range.getSheet();
  if (sheet.getSheetName() != "Search" || range.columnStart != 2 || range.rowStart != 1) return;
  const searchValue = range.getValue();
  
  // Clear cells "A4:C".
  const dataRange = sheet.getRange("A4:C" + sheet.getLastRow()).clearContent();
  
  // Put your formula `=QUERY(Sheet1!A2:C,"where C contains '"&B1&"'")` in to cell "A4".
  sheet.getRange("A4").setFormula(`=QUERY(Sheet1!A2:C,"where C contains '"&B1&"'")`);
  SpreadsheetApp.flush();
  
  // Convert the formula to text.
  dataRange.copyTo(dataRange, { contentsOnly: true });
  
  // Set text style using the search text to column "C".
  const style = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("red").build();
  const rt = dataRange.getValues().map(([, , c]) => {
    const r = SpreadsheetApp.newRichTextValue().setText(c);
    [...c.matchAll(new RegExp(`${searchValue}.*?\b`, "g"))].forEach(o =>
      r.setTextStyle(o.index, o.index + o[0].length, style)
    );
    return [r.build()];
  });
  dataRange.offset(0, 2, rt.length, 1).setRichTextValues(rt);
}

Testing:

When I tested this script using your provided Spreadsheet, the following result is obtained.

Note:

  • In this script, the simple trigger onEdit is used. If the processing time of the script is over 30 seconds, please rename the function name from onEdit to installedOnEdit. And, install the OnEdit trigger to installedOnEdit and test it again. By this, the maximum execution time is 6 minutes.

  • This script can be used to your provided Spreadsheet. When you change Spreadsheet, this script might not be able to be used. Please be careful about this.

Added:

When I saw your question, I thought that you might want to automatically run the script when a search text is put into cell “B1” of “Search” sheet. But from your following reply,

but I still get this error: TypeError: Cannot destructure property ‘range’ of ‘e’ as it is undefined. onEdit

If you want to directly run the script by the script editor, a button, a custom menu and so on, how about the following sample script?

When you use this script, please do the following flow.

  1. Copy and paste the following script to the script editor of your provided Spreadsheet and save the script.
  2. Put a search text like rare into the cell “B1” of “Search” sheet.
  3. Run the function sample by the script editor.

By this flow, the script works to your provided Spreadsheet.

function sample() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const srcSheet = ss.getSheetByName("Sheet1");
  const srcValues = srcSheet.getRange("A2:C" + srcSheet.getLastRow()).getValues();
  const dstSheet = ss.getSheetByName("Search");
  const searchValue = dstSheet.getRange("B1").getValue();
  const dstValues = srcValues.filter(([, , c]) => c.includes(searchValue));
  if (dstValues.length == 0) return;
  dstSheet.getRange("A4:C" + dstSheet.getLastRow()).clearContent();
  const dstRange = dstSheet.getRange(4, 1, dstValues.length, dstValues[0].length);
  dstRange.setValues(dstValues);
  const style = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("red").build();
  const rt = dstValues.map(([, , c]) => {
    const r = SpreadsheetApp.newRichTextValue().setText(c);
    [...c.matchAll(new RegExp(`${searchValue}.*?\b`, "g"))].forEach(o =>
      r.setTextStyle(o.index, o.index + o[0].length, style)
    );
    return [r.build()];
  });
  dstRange.offset(0, 2, rt.length, 1).setRichTextValues(rt);
}

When this script is run, the same result of the above result is obtained. But, in this case, it is requried to manually run the function. Please be careful about this.

4

Here is a snippet you could try:

function underlineWord() {
let sheet = SpreadsheetApp.getActiveSheet();
let valueToSearch = sheet.getRange("B1").getValue();
let data = sheet.getRange("G4:G").getValues().flat().filter(el => el != "");
let style = SpreadsheetApp.newTextStyle();
style.setForegroundColor("#ea4335");
let buildStyle = style.build();
let richTextValues = [];
for (let i = 0; i < data.length; i++) {
    let startIndex = data[i].indexOf(valueToSearch);
    let wordLength = valueToSearch.length;
    let richText = SpreadsheetApp.newRichTextValue();
    richText.setText(data[i]);
    richText.setTextStyle(startIndex, startIndex + wordLength, buildStyle);
    let format = richText.build();
    richTextValues.push([format]);
}

sheet.getRange(`G4:G${richTextValues.length + 1}`).setRichTextValues(richTextValues);

}

If you need other formatting or info you can refer to: Class RichTextValueBuilder

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật