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

2023-12-07

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

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() 来运行它,则会收到以下错误:

类型错误:无法调用未定义的方法“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);
}

感谢您的回复:)


为什么不直接这样做呢?我认为您遇到的参考文献问题可以通过此方法解决。

Menu:

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函数。

如果这不能满足您的目的,我们可以尝试其他方法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Apps 脚本:使用电子表格范围作为参数从菜单调用函数[重复] 的相关文章

随机推荐