javascript - 谷歌应用脚​​本: Calling a function from menu with a spreadsheet range as the parameter

标签 javascript google-apps-script google-sheets menu

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

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 - 谷歌应用脚​​本: Calling a function from menu with a spreadsheet range as the parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23823558/

相关文章:

javascript - 当 View 模型属性更改复选框值时收到通知

javascript - 如何在 JavaScript 的数组列表中找到最大的数组值

google-apps-script - Google Apps 独立脚本使用 Google Apps 脚本 API 更新许多绑定(bind)脚本

javascript - 交互式 SVG : Hover over one part, 改变另一个颜色

javascript - Google Apps脚本: Find Cells With a Certain Value,然后设置它的背景颜色

google-apps-script - 如何将 Google 表单中的响应 ID 保存到 Google 电子表格

javascript - Google 脚本 - 从网站论坛解析 HTML - 并将数据写入工作表

arrays - 使用 ID 从另一个工作表导入数据,但仅导入某些列

javascript - 按值获取单元格

javascript - HTML 更改时验证限制复选框不起作用