I want to make bold a string stored in a variable called boldtext. I want a simple one line code for this. I am not from coding background. Please help
Edit 1:
I made mistake in my original question. So, I am putting the question again.
My need = I want variable boldtext to be bold.
function calendar() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Course');
var user = Session.getActiveUser().getUsername(); //gives user name
var firstpart = user.split('.')[0]; //gives first part of user name
var uppercase = firstpart.charAt(0).toUpperCase() + firstpart.substring(1);//makes first letter upper case
var boldtext = 'Nice work, ' + uppercase //This has to be made bold
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var boldname = SpreadsheetApp.newRichTextValue().setText(boldtext).setTextStyle(boldtext.indexOf(uppercase), boldtext.length, bold).build(); //mistake is here by me.
spreadsheet.getRange('X53').setValue(boldname + 'Reminder is added to your calendar');
function myFunction() {
var user = Session.getActiveUser().getUsername();
var first = user.split('.')[0];
var name = first[0].toUpperCase() + first.substring(1);
var text = 'Nice work, ' + name;
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var value = SpreadsheetApp.newRichTextValue().setText(text).setTextStyle(text.indexOf(name), text.length, bold).build();
SpreadsheetApp.getActiveSheet().getRange('A1').setRichTextValue(value);
}
Reference
Class RichTextValueBuilder
Updated variant
function calendar() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Course');
var user = Session.getActiveUser().getUsername();
var firstpart = user.split('.')[0];
var name = firstpart[0].toUpperCase() + firstpart.substring(1);
var boldtext = 'Nice work, ' + name;
var bold = SpreadsheetApp.newTextStyle().setBold(true).build();
var text = ' Reminder is added to your calendar';
var value = SpreadsheetApp.newRichTextValue().setText(boldtext + text).setTextStyle(0, boldtext.length, bold).build();
spreadsheet.getRange('X53').setRichTextValue(value);
}
Related
How can I get the next or previous character of findText().
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var str = doc.getbody();
var i = "f";
var x = str.findText(i);
var y = str[str.index(x)-1];
Logger.log(y);
}
It is not working. and get some error.
Example: string = "Abcdefgh" , var x=string.findText("f"); after found "f"; want to get previous char of "f". which is "e" in this case. I want to know special function in google script to get
Flow:
getBody() returns a body object. You need string type. getText() returns string.
Use regexp#exec to get previous and next character of the search string
Snippet:
function myFunction() {
var doc = DocumentApp.getActiveDocument();
var str = doc.getBody().getText();//modified
var search = "f";
var regx = new RegExp("(.)"+search+"(.)")
var y = regx.exec(str);
Logger.log(y);
if (y !== null){ Logger.log("Previous character" + y[1]).log("Next character:" + y[2])}
}
To practice:
Regexp#exec
Doc#body
I have a created a slide template in which multiple teams will use to use to create an information sheet about their respective Process. This content is intended to be produced in a standardised way.
To make things easier I have created a sheet in which key information can be input into cells to populate elements of the template.
The issue I'm having is I want each process to have a different colour scheme. Is there a way I can set a cell to the desired font or background colour in sheets and then get the template to create in that colour? or even a colour scheme?
How do I single out certain text or text boxes of the slide to set the background colour?
Desired Solution
Any help is much appreciated
// Add a custom menu to the active spreadsheet, including a separator and a sub-menu.
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Templates')
.addItem('Cheat Sheet', 'createNewCase')
.addToUi();
}
function createNewCase(input) {
var category = input
var ui = SpreadsheetApp.getUi();
// get active spreadsheet
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = activeSpreadsheet.getActiveSheet();
// Check to ensure script being run from 'Option 1' sheet
if (activeSheet.getName() != "Sheet1") {
ui.alert("Active sheet must be 'Sheet1', terminating script");
return;
}
//Get active cell
var sourceRow = activeSheet.getActiveCell().getRow();
// Read case variables
var sourceProcess = activeSheet.getRange('A' + sourceRow).getValue();
var sourceName1 = activeSheet.getRange('B' + sourceRow).getValue();
var sourceName2 = activeSheet.getRange('C' + sourceRow).getValue();
var sourceTeam = activeSheet.getRange('D' + sourceRow).getValue();
var sourcePurpose = activeSheet.getRange('E' + sourceRow).getValue();
var sourceDef = activeSheet.getRange('F' + sourceRow).getValue();
var sourceColor = activeSheet.getRange('G' + sourceRow).getFontColor();
// Message prompt
var userChoice = ui.alert("You are about to generate a Cheat Sheet template for " + sourceProcess +"\n\nDo you wish to continue?\n\n",ui.ButtonSet.YES_NO);
if (userChoice == ui.Button.NO) {
ui.alert("Terminating script");
return;
}
//Set case document filename
var newFilename = sourceProcess + "Process Cheat Sheet"
//Get template folder
var templateFolder = DriveApp.getFolderById("1MCQn9_oiaaUt4_dNzr2EoDWkUGsYOH-O");
// Get case Template document
var docTemplate = DriveApp.getFileById("1cmm1ifvfRv7omGVmRhD0zunCngBcIY_qo2jpCA_sHV4");
var caseDocument = docTemplate.makeCopy(newFilename);
var caseDocumentID = caseDocument.getId();
var caseSlide = SlidesApp.openById(caseDocumentID);
var caseName1 = caseSlide.replaceAllText("%NAME1%", sourceName1);
var caseName2 = caseSlide.replaceAllText("%NAME2%", sourceName2);
var caseProcess = caseSlide.replaceAllText("%PROCESS%", sourceProcess);
var caseTeam = caseSlide.replaceAllText("%TEAM%", sourceTeam);
var casePurpose = caseSlide.replaceAllText("%PURPOSE%", sourcePurpose);
var caseDef = caseSlide.replaceAllText("%DEFINITION%", sourceDef);
// Record Case Document link
activeSheet.getRange('H' + (sourceRow)).setFormula('=HYPERLINK("' + caseDocument.getUrl() + '", "Cheat Sheet Template")');
}
How do I use appendText() or insertText() for a Google Doc script and maintain formatting?
I want to format the middle portion (group2) of appended strings with italics, while leaving the other parts (group1, group3) as normal text. For example: Hi my name is Nate.
I can bring in "Hi" and append "my name is" and it formats correctly. When I try to append (or insert) "Nate," "Nate" is italicized as well.Between operators +, appendText(), and insertText(), I'm not having much luck.
Below is the relevant portion of the script. Below that, is the entire thing.
How can I append 3 strings together, and only format the middle portion?
NOTE: I commented-out the things I tried (trial1, trial2, etc.). I also started HERE and used it as a guide.
Thanks for any help you can offer!
RELEVANT PART:
if (author1 != "") {
var group1 = author1+author2+author3;
var group2 = title2Italics+containerItalics;
var group3 = contribution1+contribution2+contribution3+version+number+publisher+pubDate+location;
//Only using the calculations below to determine the offset for insertText
var group1Length = group1.length;
var group2Length = group2.length;
var offset = group1Length+group2Length
Logger.log(group1Length);
Logger.log(group2Length);
Logger.log(offset);
//Determines if italicizing is necessary
if (group2.length > 0) {
var addG1 = body.insertParagraph(0,group1)
var addG2 = addG1.appendText(group2);
var formatItalics = addG2.editAsText().setItalic(true);
//var trial1 = addG2.editAsText().setItalic(true) + group3; //does not return the contents of "group3"
//var trial2 = formatItalics + group3; //does not return the contents of "group3"
//var trial3 = formatItalics.insertText(offset,group3); //Error: "Index (18) must be less than or equal to the content length (6)."
//var trial4 = formatItalics.insertText(group2Length, group3); //formats "group3" as well
//var trial5 = formatItalics.appendText(group3); //formats "group3" as well
}
//If italicizing is NOT necessary
else {
var cite = body.insertParagraph(0,group1 + group3);
} //ELSE STATEMENT ENDS HERE
} //FIRST IF STATEMENT ENDS HERE
ENTIRE SCRIPT:
function mlaBibTest() {
// Sheet Information
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.setActiveSheet(ss.getSheetByName('test'));
var startRow = 3;
var startCol = 21;
var numRows = sheet.getLastRow()-1;
var numCols = 14;
var dataRange = sheet.getRange(startRow, startCol, numRows, numCols);
// Document information
var doc = DocumentApp.openById('13MlHq_uoO1rUF0RfdF_kBlLJjbGt4aDoOcSWef0V4zM');
var body = doc.getBody();
// Fetch values for each row in the SS Range.
var cells = dataRange.getValues();
for (var i = 0; i < cells.length; ++i) {
var column = cells[i];
var colU = column[0];
var colV = column[1];
var colW = column[2];
var colX = column[3];
var colY = column[4];
var colZ = column[5];
var colAA = column[6];
var colAB = column[7];
var colAC = column[8];
var colAD = column[9];
var colAE = column[10];
var colAF = column[11];
var colAG = column[12];
var colAH = column[13];
var author1 = colU;
var author2 = colV;
var author3 = colW;
var title1Quotes = colX;
var title2Italics = colY;
var containerItalics = colZ;
var contribution1 = colAA;
var contribution2 = colAB;
var contribution3 = colAC;
var version = colAD;
var number = colAE;
var publisher = colAF;
var pubDate = colAG;
var location = colAH;
if (author1 != "") {
var group1 = author1+author2+author3;
var group2 = title2Italics+containerItalics;
var group3 = contribution1+contribution2+contribution3+version+number+publisher+pubDate+location;
//Only using the calculations below to determine the offset for insertText
var group1Length = group1.length;
var group2Length = group2.length;
var offset = group1Length+group2Length
Logger.log(group1Length);
Logger.log(group2Length);
Logger.log(offset);
//Determines if italicizing is necessary
if (group2.length > 0) {
var addG1 = body.insertParagraph(0,group1)
var addG2 = addG1.appendText(group2);
var formatItalics = addG2.editAsText().setItalic(true);
//var trial1 = addG2.editAsText().setItalic(true) + group3; //does not return the contents of "group3"
//var trial2 = formatItalics + group3; //does not return the contents of "group3"
//var trial3 = formatItalics.insertText(offset,group3); //Error: "Index (18) must be less than or equal to the content length (6)."
//var trial4 = formatItalics.insertText(group2Length, group3); //formats "group3" as well
//var trial5 = formatItalics.appendText(group3); //formats "group3" as well
}
//If italicizing is NOT necessary
else {
var cite = body.insertParagraph(0,group1 + group3);
} //ELSE STATEMENT ENDS HERE
} //FIRST IF STATEMENT ENDS HERE
} //FOR LOOP ENDS HERE
SpreadsheetApp.flush();
} // FUNCTION ENDS HERE
This is a simple example of doing what you asked. It's important to remember that setItalics(true) sets a persistent setting for all new text to be italic, so we have to set it back to false after.
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraph = body.insertParagraph(0, ""); //add paragparh at top of body.
var text1 = paragraph.appendText("Not Italics ");
var text2 = paragraph.appendText("Italics ");
text2.setItalic(true); //Everything after and including this will be italics
var text3 = paragraph.appendText("Not Italics");
text3.setItalic(false); //Everything after and including this will not be italics
>Not Italics Italics Not Italics
So it's easier if you set italics as you build the paragraph.
I'm trying to sending a file as e-mail attachment with Google Apps Script, following this rich answer. But instead of a stand alone app, I'm trying to do so within my spreadsheet, using a function like this:
function sendAttachment(){
var activeSheet = ss.getActiveSheet();
ScriptProperties.setProperty('emailRequest', 1);
if(!person_ID) {
person_ID = getCurrentRow();
//if the current line is the Column Headers line then ask the user to specify the ID, very rare case.
if (person_ID == 1) {
var person_ID = Browser.inputBox("Select one name.", "Click in one row:", Browser.Buttons.OK_CANCEL);
}
}
var app = UiApp.createApplication().setHeight(400).setWidth(600);
var panel = app.createVerticalPanel(); // you can embed that in a form panel
var label = app.createLabel("Choose the receiver").setStyleAttribute("fontSize", 18);
app.add(label);
var currentRow = ss.getActiveSelection().getRowIndex();
var personName = activeSheet.getRange(currentRow, 1).getValue();
var personNumber = activeSheet.getRange(currentRow, 5).getValue();
var item1Panel = app.createHorizontalPanel();
var txt = app.createTextBox().setId("item1").setName("item1").setValue(personName);
item1Panel.add(app.createLabel("Person:")).add(txt);
var item2Panel = app.createHorizontalPanel();
var txt = app.createTextBox().setId("item2").setName("item2").setValue(personNumber);
item2Panel.add(app.createLabel("Num:")).add(txt);
var sheet = SpreadsheetApp.openById(letterSpreadsheetId).getSheetByName("emailsDB");
var recipientEmailArray = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
var item3Panel = app.createHorizontalPanel();
item3Panel.add(app.createLabel("Receiver"));
var listBox = app.createListBox().setName('item3');
for(var i = 0; i < (recipientEmailArray.length); i++){
listBox.addItem(recipientEmailArray[i][0] + ": " + recipientEmailArray[i][2]);
}
item3Panel.add(listBox);
var handlerBut = app.createServerHandler("butSendAttachment").addCallbackElement(panel);
var but = app.createButton("submit").setId("submitButton4").addClickHandler(handlerBut);
panel.add(item1Panel)
.add(item2Panel)
.add(item3Panel)
.add(app.createFileUpload().setName('thefile'))
.add(app.createLabel().setId("answer"))
.add(but);
var scroll = app.createScrollPanel().setPixelSize(600, 400).setTitle("My title 1");
scroll.add(panel);
app.add(scroll);
ss.show(app);
// var handlerBut = app.createServerHandler("butSendAttachment").addCallbackElement(panel);
// .add(app.createFileUpload().setName('thefile'));
// var form = app.createFormPanel();
// form.add(panel);
// app.add(form);
;
}
function butSendAttachment(e){
var recipientEmail = e.parameter.item3;
var fileBlob = e.parameter.thefile;
Logger.log("file blob = " + fileBlob);
recipientEmail = recipientEmail.split(':')[1];
var sheet = ss.getActiveSheet();
var person_ID = getCurrentRow();
var columns = getRowAsArray(sheet, 1);
var personData = getRowAsArray(sheet, person_ID);
var sender = actAuthor + " \n " + position;
var name = personData[0];
var motherName = personData[1];
var title = "my title";
var message = my mesage";
var confirm = Browser.msgBox('Send email','Are you sure?', Browser.Buttons.OK_CANCEL);
if(confirm=='ok'){
// MailApp.sendEmail(recipientEmail, title, message, {attachments: [fileBlob]});
MailApp.sendEmail(recipientEmail, title, message, {attachments: [fileBlob]});
var app = UiApp.createApplication().setHeight(150).setWidth(250);
var msg = "An email was sendo to " + recipientEmail;
app.setTitle("E-mail send!");
app.add(app.createVerticalPanel().add(app.createLabel(msg)));
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
else {
return;
}
}
But I get this error: Execution failed: Invalid argument: inlineImages (line 77. Line 77 is this:
MailApp.sendEmail(recipientEmail, title, message, {attachments: [fileBlob]});
I've read the documentation I tried several argument variations. I conclude that fileBlob is Null. Why? How to fix it?
the fileUpload widget works only in a form parent widget and using a doGet/doPost structure.
That's written somewhere in the doc but right now I don't remember exactly where (I'look for it later)
But actually I guess you can build such a structure from within your spreadsheet, just change the names of your functions and use a formPanel as main widget. Don't forget also that you don't need a handler anymore and must use a submitButton widget.
EDIT : how silly I am ! its written in the first line in the widget's doc !!! ;-)
I am trying to replace some part of a formula in cell D3 of a spreadsheet, but I can't seem to do it. The formula in D3 is very long, but I only need to replace what would be searchtext variable and replace it with replacetext variable. Any ideas? Here's my code.
function dashboards(){
var ss1 = SpreadsheetApp.getActiveSpreadsheet();
var origSheet1 = ss1.getSheetByName('Daily');
var searchtext = Browser.inputBox("Enter search text");
var replacetext = Browser.inputBox("Enter replace text");
var form = origSheet1.getRange("D3").getFormulaR1C1();
form.indexof(searchtext);
var updated = form.replace(searchtext, replacetext);
form.setFormula(updated);}
You're not far off. The problem is that form, the below, is a String, not a reference to your Range.
var form = origSheet1.getRange("D3").getFormulaR1C1();
You can see this by inserting
Logger.log(form + "; type: " + typeof form); //String
after that line and checking the log in the Script Editor.
You just need to change
form.setFormula(updated);
to
origSheet1.getRange("D3").setFormulaR1C1(updated);
to update the actual range.
Copy the code below and run it via Script Manager or a menu item.
It operates on whatever the selected range is, whether it's a single cell or extends over multiple rows & columns.
It pops up a toast message to tell you when the procedure has finished but it leaves the UiInstance open in case you want to do more replacing.
You can keep it open and perform multiple search/replace in formulas on multiple selections or the same search on different sheets.
function handySRF() { // script composed by ailish#ahrosters.com
var ss = SpreadsheetApp.getActive();
var app = UiApp.createApplication().setHeight(200).setWidth(270).setTitle('Search and Replace In Formulas');
var panel = app.createAbsolutePanel().setId('panel').setHeight(198).setWidth(268)
.setStyleAttribute('background', 'lightCyan');
var lblSearch = app.createLabel('Search for:').setId('lblSearch');
var txtSearch = app.createTextBox().setId('txtSearch').setName('txtSearch');
var lblReplace = app.createLabel('Replace with:').setId('lblReplace');
var txtReplace = app.createTextBox().setId('txtReplace').setName('txtReplace');
var handler = app.createServerHandler('btnStartSearch');
var btnStartSearch = app.createButton('Start Search').addClickHandler(handler)
.setStyleAttribute('background', 'lightGreen');
handler.addCallbackElement(panel);
var handler2 = app.createServerHandler('btnCloseWindow');
var btnCloseWindow = app.createButton('Close Window').addClickHandler(handler2)
.setStyleAttribute('background', 'lightYellow');
handler2.addCallbackElement(panel);
panel.add(lblSearch, 10, 6)
panel.add(txtSearch, 10, 33)
panel.add(lblReplace, 10, 75)
panel.add(txtReplace, 10, 100)
panel.add(btnStartSearch, 10, 151)
panel.add(btnCloseWindow, 130, 151)
app.add(panel);
ss.show(app);
};
function btnStartSearch(e) {
var ss = SpreadsheetApp.getActive();
var app = UiApp.getActiveApplication();
var search = e.parameter.txtSearch;
var replace = e.parameter.txtReplace;
var rows = ss.getActiveSelection();
var numRows = rows.getNumRows();
var formulas = rows.getFormulas();
var newFormulas = [];
for (var i = 0; i <= numRows - 1; i++) {
var oldData = formulas[i];
var newData = [];
for (var j=0; j<oldData.length; ++j) {
var item = oldData[j].replace(new RegExp(search, "g"), replace);
newData.push(item);
}
newFormulas.push(newData);
}
rows.setFormulas(newFormulas);
var str = 'Finished replacing ' + search + ' with ' + replace;
ss.toast(str, '', 2);
};
function btnCloseWindow(e) {
var ss = SpreadsheetApp.getActive();
var app = UiApp.getActiveApplication();
app.close();
return app;
};