在 Sheet1 中我有如下数据
本年度销售额增加至 +12%
当前季度销售数量减少至 -12%
佛罗里达州销售额上升夏威夷下降
我想更改Sheet1中现有数据中特定文本的颜色。 我想要更改颜色的特定文本在我的代码中声明为数组。 数组名称为 pos_text 我正在使用 @doubleunary
的以下解决方案这是代码:
function changecolor() {
var range = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Sheet13").getRange("D2:H8");
var c_values = range.getValues();
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var count = 0;
var pos_text =['Increased','up','high','more','positive'];
var colors;
var srch_text='Increased';
Logger.log(pos_text.length);
for(i=0;i<pos_text.length;i++){
const regex = new RegExp(pos_text[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),'gi');
const num_regex = new RegExp('[-]?[0-9]\&*','gi');
const format = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor('#55883B').build();
const values = range.getDisplayValues();
Logger.log(values);
if(values!=null){
let match;
const formattedText = values.map(row => row.map(value => {
const richText = SpreadsheetApp.newRichTextValue().setText(value);
while (match = regex.exec(value)) {
Logger.log("While " + match);
richText.setTextStyle(match.index, match.index + match[0].length, format);
}
while (match = num_regex.exec(value)) {
richText.setTextStyle(match.index, match.index + match[0].length, format);
}
return richText.build();
}));
range.setRichTextValues(formattedText);
}
}
}
根据此Google表格中的粗体特定文本中给出的解决方案 传递单个文本,而是我想传递数组列表。为此,我尝试了粘贴的上述代码,我修改的代码仅更改数字而不更改文本。不知道我错过了什么。
虽然我不确定你的显示脚本修改后是否能正确理解你的预期结果,但修改如下怎么样?
请将您的范围设置为
rangeA1Notation
作为 A1Notation。
function formatPhraseInText() {
const rangeA1Notation = "'Sheet13'!D2:H8";
const pos_text = ['Increased', 'up', 'high', 'more', 'positive'];
const range = SpreadsheetApp.getActiveSpreadsheet().getRange(rangeA1Notation);
const format = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor('blue').build();
const values = range.getDisplayValues();
let match;
const formattedText = values.map(row => row.map(value => {
const richText = SpreadsheetApp.newRichTextValue().setText(value);
pos_text.forEach(t => {
const regex = new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
while (match = regex.exec(value)) {
richText.setTextStyle(match.index, match.index + match[0].length, format);
}
});
return richText.build();
}));
range.setRichTextValues(formattedText);
}
运行此脚本,得到以下结果。