javascript-Google Apps脚本:使用电子表格范围作为参数从菜单中调用函数
作者:互联网
我有一个函数,该函数接受电子表格范围作为参数,然后在与给定范围相同的行中添加日期.
function autoDate(cell) {
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
var currentDateStr = new String();
currentDateStr = currentDate.getDate() + "/" + currentMonth;
var sheet = SpreadsheetApp.getActiveSheet();
if (cell.getValue() == ""){
var activeRowInt = cell.getRow();
var dateCell = sheet.getRange(activeRowInt,3); //3 is my date column
dateCell.setValue(currentDateStr);
}
}
我有一个菜单,在其中运行一个单独的函数,该函数以活动单元格作为参数调用autoDate()(因为菜单系统不允许使用参数来调用函数)
function autoDateMenu(){
var sheet = SpreadsheetApp.getActiveSheet();
var activeCell = sheet.getActiveCell();
autoDate(activeCell);
}
如果我从脚本编辑器中运行autoDateMenu(),它将正常工作.
如果我通过从电子表格的菜单中选择autoDateMenu()来运行它,则会出现以下错误:
TypeError: Cannot call method “getValue” of undefined. (line 64, file
“Code”)
第64行是指以下行:
if (cell.getValue() == ""){
这是我为菜单编写的代码:
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
},{
name : "Set Date",
functionName : "autoDateMenu"
}];
spreadsheet.addMenu("Script Center", entries);
}
感谢您的回复:)
解决方法:
为什么不这样做呢?我认为您的参考文献存在问题,可以解决此问题.
菜单:
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
},{
name : "Set Date",
functionName : "autoDate"
}];
spreadsheet.addMenu("Script Center", entries);
}
自动约会功能:
function autoDate() {
var sheet = SpreadsheetApp.getActiveSheet();
var activeCell = sheet.getActiveCell();
var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
var currentDateStr = new String();
currentDateStr = currentDate.getDate() + "/" + currentMonth;
if (activeCell.getValue() == ""){
var activeRowInt = cell.getRow();
var dateCell = sheet.getRange(activeRowInt,3); //3 is my date column
dateCell.setValue(currentDateStr);
}
}
删除中间人的AutoDateMenu函数.
如果这不能满足您的目的,我们可以尝试其他方法.
标签:javascript,google-sheets,google-apps-script,google-apps-script-menu 来源: https://codeday.me/bug/20191009/1878675.html