Bold conditional formatting script for Google Spreadsheets - google-apps-script

What I want to do is essentially what this user wanted to do here:
I need a script that formats the cells in column A bold, but only the cells that contain the word 'Hello'.
However I have no knowledge of Google Apps scripts at all, and I need an answer put in much simpler terms than what I could find there or anywhere else. Any help is appreciated; thank you!

To start, from your spreadsheet, open "Tools / Script Editor...". When the dialog opens, choose to "Create Script For... Spreadsheet". You will end up with a sample script - we're going to edit it to do what you want.
Change the readRows() function as shown here. The change is that instead of logging the content of every row, we will use an if statement to check if the cell contains a string with 'Hello' in it. Then, if it does, we'll bold the cell text.
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
// Arrays start at 0, Google Sheets start at 1 - must remember that.
// We will loop starting at 1, because we want to skip the header in
// Row 1, aka Array index 0
for (var i = 1; i <= numRows - 1; i++) {
var colA = values[i][0];
if (colA.toString().indexOf('Hello') >= 0) {
sheet.getRange(i+1,1).setFontWeight("bold");
}
}
};
Now, how to run that? The sample already has an onOpen() function that will set up a custom menu... let's just change the text it displays in the User Interface, as shown here. The only change is in the 'name' property of the menu entries.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Bold Hello",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};
Save your script. Go back to your spreadsheet, and reload it (to get it to run the onOpen trigger function). When your menu shows up, you're all set.
Next - start with the "First Script" tutorial here. The Google Apps Script documentation covers all the services provided by Apps Script, but the basic language structure and objects are javascript, so you should get familiar with that. Just try googling "learn javascript", and you'll find tons of tutorials, books, and other resources.
I can't make this simpler.

In the now not so new 'New' Sheets this can be achieved without a script:
Clear formatting, select ColumnA and Format, Conditional formatting..., Format cells if... Text contains and:
hello
Then for Formatting style click the B and Done.
This way is not case sensitive and will embolden contents such as OTHELLO.

If you aren't trying to set too many conditional formatting rules, there's an easier way to set colors, though not bold. In Google Drive Spreadsheet, click the "Format" menu. The bottom menu item should be "Conditional formatting..."; click that. That should produce a dialog box that defaults to something like this (to the extent that I can draw it with text):
x
Conditional formatting
[Text contains ◊ ] [ ] []Text: [ ] []Background: [ ] x
e.g. "done" or "Jonathan"
_______________________________________________________________________________
+ Add another rule
[ Save rules ] [ Cancel ]
In your example, you're looking for cells that contain "Hello", so the default of "Text contains" would do the job. Put "Hello" into the text box, and set a format in the "Text":" and "Background:" boxes. That doesn't give you bold, but it does allow colors.
I see that your question dates back half a year, so it's probably too late for you (and if you strictly need bold, it doesn't solve the problem anyway), but it may help others.

Related

Show and hide selected columns with single macro in google sheets

Starting out like all others. I am new to macros and I know what I'm trying to do is easy, but I can't get it working.
So I'm making buttons on a spreadsheet to show and hide columns, if the column is hidden then show, if the column is shown then hide. So a toggle button between show and hide basically.
I will continue to research while this is here as I'm sure the answer is simple. Just an If, then, else but I'm a noob.
Any help would be appreciated. Here's one of the 'show' ones I have if it's easier to edit that.
Thanks
function ShowCA() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getActiveSheet().showColumns(6);
};
I believe your goal is as follows.
About the column "F", when the column is showing, you want to hide the column. When the column is hiding, you want to show the column.
You want to achieve this using a function of Google Apps Script.
In this case, I thought that isColumnHiddenByUser can be used. So, how about the following sample script?
Sample script:
function ShowCA() {
var column = 6; // This is column "F".
var sheet = SpreadsheetApp.getActive().getActiveSheet();
if (sheet.isColumnHiddenByUser(column)) {
sheet.showColumns(column);
} else {
sheet.hideColumns(column);
}
}
When this script is run, when the column "F" is showing, the column is hidden. When the column "F" is hiding, the column is shown.
References:
isColumnHiddenByUser(columnPosition)
showColumns(columnIndex)
hideColumns(columnIndex)

How can I have the text I enter into each cell automatically appended to the same root URL without creating any new columns?

I am rephrasing my original question to make it more intelligible.
I put spaces between "https" below because StackOverflow would not allow me to enter the actual URL.
Of course I could enter the text "apple" in cell A1 and then add a link from A1 to foo.com/Apple so that I would end up with [Apple](h t t p s://foo.com/Apple) in A1. However, I want that done automatically.
In other words, I want to...
Go to a cell, and then
type "apple" on my keyboard, and then
press enter, and then
instead of merely seeing "apple" in plain text, I actually I want to see
"apple" hyperlinked to foo.com/Apple like this [Apple](h t t p s://foo.com/Apple).
To get what you want you can use Google Apps Script. Adding a trigger that fires every time column A is edited, getting the entered value and combining it with the =HYPERLINK(url, link_label) function, should get what you need.
Open the Google Apps Script editor, Tools>Script Editor
Add the following code
function onEdit(e) {
// Check the edit is in column A
if(e.range.getColumn()==1){
// Get the values from the onEdit
let cell = e.range.getA1Notation()
let value = e.value
let ss = e.source
// Adding as HYPERLINK Formulas
ss.getRange(cell)
.setFormula(`=HYPERLINK("https://example.com/${value}","${value}")`)
}
}
Documentation
HYPERLINK Function
onEdit(e) Trigger
SpreadSheetApp Overview
try:
=INDEX("foo.com/"&B2:B3)

Problem, merging cell in a table document, google apps script [duplicate]

I've writen this function (thanks, #Mogsdad) to merge cells in a table in a text google document, like this:
function onOpen() {
// Add a menu with some items, some separators, and a sub-menu.
DocumentApp.getUi().createMenu('Sample')
.addItem('merge cells of a table', 'mergeCells')
.addToUi();
}
function mergeCells() {
var body = DocumentApp.getActiveDocument().getBody();
for (var p= 0; p< body.getNumChildren(); p++) {
var child = body.getChild(p);
if (child.getType() == DocumentApp.ElementType.TABLE){
// Assume we've already located our table
var table = child;
var tableRow = table.getChild(2); // gets third row
var tableCell = tableRow.getChild(1); // gets second cell in row
tableCell.merge(); // Merges seconde cell with first cell.
}
}
}
But when I run the code, I got this weird result (very different of the expected, with the merged cell with the same dimensions of the table):
Is there a way to fix it? (merged cell with the same dimensions)
[edit to address updates in Google Docs]
This currently not possible. You can know if a cell is merged by looking calling getColSpan and getRowSpan but there are no setter methods.
Please star the following issue to be notified by updates regarding this.
The merge function you found is not specific to table cells, it is there to merge any element with a previous sibling of the same type, joining their content.
[original answer]
If you were expecting to have a merged cell that, like what you can do in a spreadsheet, that is not possible. Simply because that's not possible in Google Documents (at least not yet). Therefore the API cannot do this (it can only do things that are also possible manually).
This merge function is not specific to table cells as you probably imagined. It is working as designed.
You can do this by a workaround. Add a drawing and add a table in this drawing document. In this document te option 'merge cell's' is a possibility if you select 2 cells and press the right mouse button. See this youtube video for a tutorial
Use the Advanced Documents Service, batchUpdate and mergeTableCells.
function mergeCells() {
const documentId = 'DOCUMENT_ID';
const resource = {
requests: [
{
"mergeTableCells": {
"tableRange": {
"tableCellLocation": {
"tableStartLocation": {
"index": 2
},
"rowIndex": 0,
"columnIndex": 0
},
"rowSpan": 1,
"columnSpan": 2
}
}
}
]
}
Docs.Documents.batchUpdate(resource, documentId);
}
Resources
https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services
MergeTableCellsRequest
One workaround is to embed tables within tables instead of merging cells. That way you can still programmatically add or remove cells/rows without ruining the tables. If you set the cell padding to 0, any stray paragraphs to 1pt font and remove any cell borders and you can achieve almost the same effect without any merged cells.
For example, I've got a cell with 4 columns, where I want the last column to be merged as as a single cell. I also want to be able to add or remove rows with Apps Script.
Table embedded within a table:
This way I can add or remove rows from the embedded table on the left and the right cell will remain "merged". You will have trouble getting the cell borders to line up, but if you can do without them you can still get it looking nice, like this:
And without borders:
Here is how to solve the merged cell in tables of a MS document when converting to a Google document: The idea is to go back to the MS word document and remove the merged cells and then copy and paste it or convert MS word to Google document. In this way we can get easy conversion of tables in MS documents to Google documents. But, within Google documents the cell can't be merged.

Prompt box, ask value, store in cell. Add button for adapt

I'm new to the world of google sheets. I was able to program very simple routines in Excel. Sorry if I couldn't find the answer anywhere on this site.
My question is simple, has 2 parts:
I would like to prompt a question box on opening the google sheet, asking a numeric value, after answering this, storing the numeric value to a specific cell, e.g. B3.
I would like to have a button on multiple pages of the sheet, prompting the same question box to edit the value.
Background:
I'm a medical doctor, I've created a sheet with many medications for small children in emergency situations. I would like a ask the user the age (and maybe later the weight, it's now calculated) of the child, so the age and weight are correct on all pages and the user is not in a hurry to find the right cell. If the user would like to edit the age, he uses the button, available on all sheets.
First, with the following function you can ask the user for the age and set it to a specific cell in a specific sheet:
function promptUserAge()
{
// Prompt for the value
var age = SpreadsheetApp.getUi().prompt("Please enter the age.").getResponseText();
// Get the sheet that you want store the value in and set the value in the cell B3
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Patient Information").getRange("B3").setValue( age );
}
Now, since you used the phrase
so the age and weight are correct on all pages
I am not sure if you are going to set the value in multiple sheets, and are you going to do that with Sheets functions or app script. That is why I am going to include the method to set the value in all sheets, in specific cell:
function promptUserAge()
{
// Prompt for the value
var age = SpreadsheetApp.getUi().prompt("Please enter the age.").getResponseText();
//Get all pages in spreadsheet and iterate through
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i = 0; i < sheets.length; i++ )
{
//Set the value in the cell B3 of the page
sheets[i].getRange("B3").setValue( age );
}
}
To get the prompt to pop-up when user opens the Spreadsheet you use call it in the onOpen function:
function onOpen(e)
{
promptUserAge();
}
And now, the part where you add the button to edit the value.
You could add a custom menu that would appear in the Spreadsheet's toolbar with a custom menu like this :
function createMenu()
{
SpreadsheetApp.getUi().createMenu("Fill information")
.addItem("Age", "promptUserAge")
.addToUi();
}
This is a good way if your users know what to look for, meaning that you have told them the custom menu exists. From my experience, some people have trouble finding the menu even if you tell them it is there, so since your background suggests you want to create an easy and fast way I would use the second method:
You could insert an image to the Spreadsheet by navigating from it's toolbar: Insert -> Image. Insert an Image that says 'Push here to edit information' in a very clear way and right click the image. You get the borders to edit the image size and in it's upper-right corner appears three dots. You click the dots and then "Assign script...". To the prompt, insert the function name without the parenthesis. In this example you would insert:
promptUserAge
Now the image works as a button to call the function.
I hope this helped.

How to merge the two cells of a table in a Google text Document without this weird result?

I've writen this function (thanks, #Mogsdad) to merge cells in a table in a text google document, like this:
function onOpen() {
// Add a menu with some items, some separators, and a sub-menu.
DocumentApp.getUi().createMenu('Sample')
.addItem('merge cells of a table', 'mergeCells')
.addToUi();
}
function mergeCells() {
var body = DocumentApp.getActiveDocument().getBody();
for (var p= 0; p< body.getNumChildren(); p++) {
var child = body.getChild(p);
if (child.getType() == DocumentApp.ElementType.TABLE){
// Assume we've already located our table
var table = child;
var tableRow = table.getChild(2); // gets third row
var tableCell = tableRow.getChild(1); // gets second cell in row
tableCell.merge(); // Merges seconde cell with first cell.
}
}
}
But when I run the code, I got this weird result (very different of the expected, with the merged cell with the same dimensions of the table):
Is there a way to fix it? (merged cell with the same dimensions)
[edit to address updates in Google Docs]
This currently not possible. You can know if a cell is merged by looking calling getColSpan and getRowSpan but there are no setter methods.
Please star the following issue to be notified by updates regarding this.
The merge function you found is not specific to table cells, it is there to merge any element with a previous sibling of the same type, joining their content.
[original answer]
If you were expecting to have a merged cell that, like what you can do in a spreadsheet, that is not possible. Simply because that's not possible in Google Documents (at least not yet). Therefore the API cannot do this (it can only do things that are also possible manually).
This merge function is not specific to table cells as you probably imagined. It is working as designed.
You can do this by a workaround. Add a drawing and add a table in this drawing document. In this document te option 'merge cell's' is a possibility if you select 2 cells and press the right mouse button. See this youtube video for a tutorial
Use the Advanced Documents Service, batchUpdate and mergeTableCells.
function mergeCells() {
const documentId = 'DOCUMENT_ID';
const resource = {
requests: [
{
"mergeTableCells": {
"tableRange": {
"tableCellLocation": {
"tableStartLocation": {
"index": 2
},
"rowIndex": 0,
"columnIndex": 0
},
"rowSpan": 1,
"columnSpan": 2
}
}
}
]
}
Docs.Documents.batchUpdate(resource, documentId);
}
Resources
https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services
MergeTableCellsRequest
One workaround is to embed tables within tables instead of merging cells. That way you can still programmatically add or remove cells/rows without ruining the tables. If you set the cell padding to 0, any stray paragraphs to 1pt font and remove any cell borders and you can achieve almost the same effect without any merged cells.
For example, I've got a cell with 4 columns, where I want the last column to be merged as as a single cell. I also want to be able to add or remove rows with Apps Script.
Table embedded within a table:
This way I can add or remove rows from the embedded table on the left and the right cell will remain "merged". You will have trouble getting the cell borders to line up, but if you can do without them you can still get it looking nice, like this:
And without borders:
Here is how to solve the merged cell in tables of a MS document when converting to a Google document: The idea is to go back to the MS word document and remove the merged cells and then copy and paste it or convert MS word to Google document. In this way we can get easy conversion of tables in MS documents to Google documents. But, within Google documents the cell can't be merged.