Google Apps脚本:使用电子表格范围作为参数从菜单调用函数

Google Apps Script: Calling a function from menu with a spreadsheet range as the parameter

本文关键字:参数 菜单 函数 调用 范围 脚本 Apps 电子表格 Google      更新时间:2023-09-26

我有一个函数,它接受电子表格范围作为参数,然后在给定范围的同一行中添加一个日期。

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:不能调用未定义的getValue方法。(第64行,文件"代码")

第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);
}

AutoDate功能:

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功能。

如果这对你的目的不起作用,我们可以尝试其他方法