[英]How to make trigger script work in google sheets?
My intention is to generate a random number on a specific cell everytime I select anything on my sheet.我的意图是每次我在工作表上 select 时在特定单元格上生成一个随机数。 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")
当我执行上面的代码时,我得到了这样的错误
TypeError: Cannot read property 'range' of undefined (line 7, file "triggers")
this is my first time utilizing script tool in sheets这是我第一次在工作表中使用脚本工具
How about this answer?这个答案怎么样?
onSelectionChange
is the function for the simple trigger. onSelectionChange
是简单触发器的 function。 And e
of onSelectionChange(e)
is the event trigger.onSelectionChange(e)
e
e 是事件触发器。 When the event is fired, e
has the value.e
具有值。 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.Cannot read property 'range' of undefined
,我认为您可能会在脚本编辑器中直接运行 function onSelectionChange
。 In this case, the event object is not given.range.set(RAND());
range.set(RAND());
might be range.setValue(RAND());
range.setValue(RAND());
. range.getCell(1, 1).getValue() === ""
can be modified to range.isBlank()
.range.getCell(1, 1).getValue() === ""
可以修改为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.onSelectionChange
由简单的触发器运行。RAND()
works.RAND()
有效。 When you want to put the value of RAND()
to the cell "A1" when the cell is selected, how about the following script?当您想在选中单元格时将
RAND()
的值放入单元格“A1”中,下面的脚本怎么样?
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.