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.
- Put a search text like
rare
into cell “B1” of “Search” sheet. - Clear cells “A4:C”.
- Put your formula
=QUERY(Sheet1!A2:C,"where C contains '"&B1&"'")
in to cell “A4”. - Convert the formula to text.
- 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 fromonEdit
toinstalledOnEdit
. And, install the OnEdit trigger toinstalledOnEdit
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.
- Copy and paste the following script to the script editor of your provided Spreadsheet and save the script.
- Put a search text like
rare
into the cell “B1” of “Search” sheet. - 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