Google Apps Script:使用电子表格范围作为参数从菜单调用函数 [英] Google Apps Script: Calling a function from menu with a spreadsheet range as the parameter
问题描述
我有一个函数,它接受一个电子表格范围作为参数,然后在给定范围的同一行中添加一个日期.
I have a function that accepts a spreadsheet range as a parameter, then adds a date in the same row as the given range.
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()(因为菜单系统不允许使用参数调用函数)
I have a menu where I run a separate function that calls autoDate() with the active cell as the parameter (since the menu system doesn't allow calling functions with parameters)
function autoDateMenu(){
var sheet = SpreadsheetApp.getActiveSheet();
var activeCell = sheet.getActiveCell();
autoDate(activeCell);
}
如果我从脚本编辑器中运行 autoDateMenu(),它工作正常.如果我通过从电子表格的菜单中选择它来运行 autoDateMenu(),我会收到以下错误:
If I run autoDateMenu() from within the script editor, it works fine. If I run autoDateMenu() by selecting it from the menu of the spreadsheet, I get the following error:
类型错误:无法调用未定义的方法getValue".(第 64 行,文件"代码")
TypeError: Cannot call method "getValue" of undefined. (line 64, file "Code")
第 64 行是指这一行:
Line 64 refers to this line:
if (cell.getValue() == ""){
这是我为菜单编写的代码:
Here's the code I wrote for the menu:
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Read Data",
functionName : "readRows"
},{
name : "Set Date",
functionName : "autoDateMenu"
}];
spreadsheet.addMenu("Script Center", entries);
}
感谢回复:)
推荐答案
为什么不直接这样做?我认为您遇到了可以解决的参考问题.
Why not just do this? I think you are having issues with references that this would solve.
菜单:
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 功能.
Remove the middle man AutoDateMenu function.
如果这不符合您的目的,我们可以尝试其他方法.
If this does not work for your purposes we can try something else.
这篇关于Google Apps Script:使用电子表格范围作为参数从菜单调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!