How to setup the "onChange" trigger in Google Sheet script editor - google-apps-script

I need to get a Google sheet's cell background color hex code into that same cell.
This is the function I currently use:
function BGHEX(row, column) {
var background = SpreadsheetApp.getActive().getDataRange().getCell(row, column).getBackground();
return background;
}
Now I have 2 issues:
I need the function to run again when the cell's background color is edited. I know I need to use the installable trigger "onChange" but no idea how to set it up.
I need this script & function to run on a duplicate of this Google Sheet file (meaning other sheet id's).
Thanks in advance for your help!

Follow these steps to setup an onChange trigger in your spreadsheet
Open your Apps Script project.
At the left, click Triggers alarm.
At the bottom right, click Add Trigger.
Select and configure the type of trigger you want to create.
Click Save.
Your trigger setup should look like this:
To detect background change in your spreadsheet, you need to have an Event Object to determine which changeType the user made. For this scenario, we need 'FORMAT'.
Also, to change the background color of a cell or range, the user must click or highlight the range. Using getActiveRange() will help us determine which range is being edited.
Code:
function onBGChange(e) {
if(e.changeType == 'FORMAT')
Logger.log(SpreadsheetApp.getActive().getActiveRange().getBackground());
}
Example:
Here I change the background color of A1
Output:
Executions Tab:
To apply this to another spreadsheet, you need to replicate the code and trigger set up. A script is bound to the spreadsheet where it was created and functions like getActive() and getActiveRange() will only work on the spreadsheet the script was bound to.
References:
Installable Triggers
Event Object
getActiveRange()

Related

How do i copy a checkbox value and keep the cell editable in Google Sheets?

I've posted this question 2 days ago but with no answers. Here's a link to a copy of the file I'm working on:
https://docs.google.com/spreadsheets/d/1TCQ0cWulb8Wm63Hs57ruwEXgpP1swKAi/edit?usp=sharing&ouid=110569351169109673921&rtpof=true&sd=true
Basically, what I've done is: the "effettivo" page is a copy of the "pianificazione" page, with all the cells in "effettivo" that copy its value from its relative. The trouble is: for the checkboxes on the right, the formula I've set (=pianificazione!G3, for example) copies the value but it renders the checkbox itself uneditable manually (= I can't click on the checkbox to change the value of that checkbox). I need to find a way to copy all those checkbox values from "pianificazione" to "effettivo" while mantaining the checkboxes themselves editable. Thanks again guys :)
First of all the document you provided is not Google sheet, but Excel sheets. To make checkboxes (or in my example whole data) two-ways editable from both sheets and show the same values in both sheets everytime. I suggest you save this document as Google sheet and use GAS onEdit() function. With this function you also able to mirror other changes in values, not only checkboxes. I built fast example based on your document here
or you can just take over the function to your document
function onEdit(e) {
var sheet = e.range.getSheet();
var value = e.value;
if (sheet.getName() == 'effettivo') {
e.source.getSheetByName('pianificazione').getRange(e.range.rowStart, e.range.columnStart).setValue(value);
}
if (sheet.getName() == 'pianificazione') {
e.source.getSheetByName('effettivo').getRange(e.range.rowStart, e.range.columnStart).setValue(value);
}
}
Important! delete all formulas, that passes values between sheets, since that will be done by function, you don't need them anyway. Or just delete old 'effettivo' sheet and duplicate the 'pianificazione' and rename it to 'effettivo'. Also very important to authorize script first, best way to do it in Script editor trigger onEdit function manually and authorize it.

Copy the text of a cell after an hyperlink click to another cell

I have a list and all the text is hyperlinked to the same cell in the same sheet.
Is there any way to copy the text of the cell you've clicked to the other cell?
A B
=HYPERLINK("...range=B1";"apple")
=HYPERLINK("...range=B1";"banana")
=HYPERLINK("...range=B1";"pear")
=HYPERLINK("...range=B1";"melon")
Explanation:
Your goal is to click/select a cell and get the value copied to the next cell in the same row.
You can use a onSelectionChange trigger to achieve your goal.
Solution:
Copy this code to the script editor:
function onSelectionChange(e) {
if(e.range.getColumn()==1){
e.range.offset(0,1).setValue(e.range.getValue());
}
}
Illustration:
Updated code based on OPs comment:
Copy all hyperlinks to cell B1:
function onSelectionChange(e) {
if(e.range.getColumn()==1){
e.source.getActiveSheet().getRange('B1').setValue(e.range.getValue());
}
}
Please Note!
Users have reported in the IssueTracker that onSelectionChange trigger does not work for them and it didn't work for me either. However, after I tried the recommendation steps by the google guy (you can find them in the link also) it worked:
However, I managed to get the trigger to work correctly by
deactivating V8 runtime, closing the Apps Script project and the
document, and finally, reopening the document and reactivating the V8
runtime.

Google script embedded in google sheet adding a menu item

What I tried is adding some functionality to my google sheet (creating events and pushing them to the google calendar). Everything works, but when I close the script editor my menu disappears.
I created the menu items like so:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Sync to Calendar')
.addItem('Create Events Now', 'CreateEvent')
.addItem('Delete All Events in Calendar', 'DeleteAllEvents')
.addToUi();
}
That works just fine, but I would like to close the script and also when I share the spreadsheet, the member shall be presented with the menu to click and execute the functions. Anyone has a solution how to make that permanent? (without publishing the script which would be an overkill in my opinion)
In some cases OnOpen doesn't run automatically unless the editor has authorized the script. In this case, you need to give editors a way to trigger the script, so they may authorize it, before onOpen will run automatically. You can either give them instructions to do this manually through the script editor, or you can insert a "button" into the sheet.
To do this "button" - insert an drawing into the sheet (the "button"), bind the drawing to your script, and have first time users click the drawing.
In your spreadsheet, click "Insert" -> "Drawing"
Draw a "button" image with useful text for end users ("Show custom menu" or "No menu? Click here!", etc.)
Place the drawing on your spreadsheet in a visible/convenient location.
Click the "three dots" on the drawing and select "Assign Script"
Enter the name of the function (eg OnOpen)
If a user opens the sheet and doesn't see your menu, they can click this "button" to activate the script. They'll be prompted to authorise the script as needed, then the menu will show from that point forward. They should only need to click the button the very first time they open the sheet, unless the scopes change or they manually remove authorization in account settings.
onOpen is a reserved word for a function to be called automatically when a Google Sheets spreadsheet is opened by the spreadsheet owner or editors, it will not run for viewers.
You should check that in the project there isn't any other function named onOpen otherwise another function declaration could be executed instead of the one that you expect.
Reference
https://developers.google.com/apps-scripts/guides/triggers
The suggested answer from Cameron Roberts works as a workaround.
Although in my case the problem was that the script trigger for onOpen was missing. I had to edit the script trigger within the script I wrote. In the script editor go to "Edit" -> "Current projects triggers" and add a trigger for the onOpen function with an event "on open". Apparently that was missing in my case, after that edit, it worked like a charm.

How can you monitor for click events in Google Apps script for spreadsheets?

I'm managing a Google spreadsheet with a script. onEdit is working - I can colour a cell red by putting
SpreadsheetApp.getActiveRange().setBackgroundRGB(255, 0, 0);
in the onEdit function. I would like to put the same code in a onClick function, so that when a user clicks on a cell it immediately turns red. Is this possible? I can't find any way to do it in the documentation.
As stated on the comments above before there's no way (right now) to create an onClick() function for Google Spreadsheets. That makes sense due to the fact that the google app script functions are processed in the server, the amount of load generated by onClick() events execution would make pretty easy to deplete all the quota of requests provided by default.
You should be using the documentation for creating a button and clicking on it.
You can get closer....Create a validation for the cells with an option...like "Done". Click the dropdown, select Done. now create a trigger onChange or onEdit to fire. You can get a cell/range contextualized function....like firing on a row or column. This is easy to replicate and program for
You can add a Drawing as a button - https://developers.google.com/apps-script/guides/menus#clickable_images_and_drawings_in_google_sheets
I believe the new trigger onSelectionChange(e) will achieve this. It's in the docs but at time of writing isn't yet working on my sheet. https://developers.google.com/apps-script/guides/triggers?hl=en
Try this for a click event:
function onSelectionChange(e) {
e.source.toast('Sheet: ' + e.range.getSheet()(.getName() + ' Range: ' + e.range.getA1Notation());
}
Create a "Drawing" with background transparent; then move and place the drawing on top of the cell you need and then assign the script to the drawing.

onEdit function

in google apps script, how can I automatically run a script when I change the background color of a cell?
When I change the background color of a cell, the spreasheet is automatically saved and it says also when last edit was made, but if I try to use this event on an onEdit function to run a script, it doesn't recognize the event and does nothing. Thanks
onEdit is going to fire when any cell value changes, not with any formatting changes. You'll have to place the rules to change the bg colors in the script, assuming that the rules are based on cell values already in the sheet.
I'm afraid you'll have to manage this using a 'trick' as there is indeed no automatic trigger for background color changes.
Just a suggestion : If your spreadsheet is not too big you could simply memorize the whole color description in a string you previously stored in script properties and, based on a timer trigger, check if something has changed.
If this solution is acceptable for you (the timer trigger and not an immediate reaction) give it a try...
Use this var for example :
var backGroundString = SpreadsheetApp.getActiveSheet().getDataRange().getBackgrounds().toString()
and compare it to the same value stored in scriptProperties, if different, trigger your event...
I know it's a bit clunky but right now I see no other simple way to get what you want.
You could add a few conditions to make it work only at some moments or when the spreadsheet is open...