- You want to add the text to the top of text in the cell and put it to the cell.
- In this case, you want to keep the text style of the original text.
- You want to change the text style of the added text to "bold" and "ForegroundColor".
- You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as justo one of several possible answers.
Modification points:
When the value is put using setValue
, it seems that the text style is cleared. This might be the specification. So in this case, in order to set the text style, I used Class TextStyleBuilder and Class RichTextValueBuilder. The flow of this modified script is as follows.
- Retrieve the cell range.
- Create the text style of additional texts which are
newContent
and space
.
- Retrieve the text style of the original texts which is
oldContent
.
- Create new RichTextValueBuilder.
- Set new texts to RichTextValueBuilder.
- Set the text style to RichTextValueBuilder.
- Put RichTextValueBuilder to the cell.
Modified script:
When your script is modified, it becomes as follows. Please select a cell including oldContent
and run the script. By this, newContent
and space
are added to oldContent
, and the text styles are set.
function CreateIssue() {
var spreadsheet = SpreadsheetApp.getActive();
var cell = spreadsheet.getCurrentCell();
var oldContent = cell.getValue();
var newContent = 'Group:\n\nDescription:\n\nExpected Results:\n\nActual Results:\n\nTest Results:\n\nTest Data:';
var space = " ";
// I added below script.
var newStyles = [{
start: 0,
end: newContent.length,
style: SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor("green").build()
}];
var richTextValue = cell.getRichTextValue();
var offset = newContent.length + space.length;
var oldContent = richTextValue.getText();
if (oldContent.length > 0) {
richTextValue.getRuns().forEach(function(e) {
newStyles.push({
start: offset + e.getStartIndex(),
end: offset + e.getEndIndex(),
style: e.getTextStyle()
});
});
}
var richText = SpreadsheetApp.newRichTextValue().setText(newContent + space + oldContent);
newStyles.forEach(function(e) {richText.setTextStyle(e.start, e.end, e.style)});
cell.setRichTextValue(richText.build());
}
- In above script, the additional text is put as the bold and green color. About this, when you want to change the color, please modify it.
Result:
When var newContent = "foo";
is set and select a cell including the text of "bar" which has the text style and run the above script, the following result can be obtained.
The original text style is kept and the additional text has the text style.
References:
If I misunderstood your question and this was not the direction you want, I apologize.