Google Apps Script: Calling a function from menu w

2019-02-20 07:28发布

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

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

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:

TypeError: Cannot call method "getValue" of undefined. (line 64, file "Code")

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

Thanks for responding :)

1条回答
Deceive 欺骗
2楼-- · 2019-02-20 07:42

Why not just do this? I think you are having issues with references that this would solve.

Menu:

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:

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

Remove the middle man AutoDateMenu function.

If this does not work for your purposes we can try something else.

查看更多
登录 后发表回答