Reputation: 329
My intention is to generate a random number on a specific cell everytime I select anything on my sheet. So what should I do in order to make this code below work?
/**
* The event handler triggered when the selection changes in the spreadsheet.
* @param {Event} e The onSelectionChange event.
*/
function onSelectionChange(e) {
// Set background to red if a single empty cell is selected.
var range = e.range;
if(range.getNumRows() === 1
&& range.getNumColumns() === 1
&& range.getCell(1, 1).getValue() === "") {
range.set(RAND());
}
}
when I execute the code above I just got error like this TypeError: Cannot read property 'range' of undefined (line 7, file "triggers")
this is my first time utilizing script tool in sheets
Upvotes: 1
Views: 568
Reputation: 201573
How about this answer?
onSelectionChange
is the function for the simple trigger. And e
of onSelectionChange(e)
is the event trigger. When the event is fired, e
has the value. So from your error message of Cannot read property 'range' of undefined
, I thought that you might be directly run the function onSelectionChange
at the script editor. In this case, the event object is not given. By this, such error occurs.range.set(RAND());
might be range.setValue(RAND());
.range.getCell(1, 1).getValue() === ""
can be modified to range.isBlank()
.When above points are reflected to your script, it becomes as follows.
/**
* The event handler triggered when the selection changes in the spreadsheet.
* @param {Event} e The onSelectionChange event.
*/
function onSelectionChange(e) {
// Set background to red if a single empty cell is selected.
var range = e.range;
if(range.getNumRows() === 1
&& range.getNumColumns() === 1
&& range.isBlank()) { // Modified
range.setValue(RAND()); // Modified
}
}
onSelectionChange
is run by the simple trigger.RAND()
works.When you want to put the value of RAND()
to the cell "A1" when the cell is selected, how about the following script?
function onSelectionChange(e) {
e.range.getSheet().getRange("A1").setValue(RAND());
}
As a sample situation, when this script is used, the following result can be seen.
function onSelectionChange(e) {
e.range.getSheet().getRange("A1").setValue(Math.random());
}
Upvotes: 1