mrC0der
mrC0der

Reputation: 25

Trying to assign function variables google apps script

I'm relatively new to Google Apps Script but I'm learning fast, and right now I'm trying to call a function with a menu, however I cannot seem to find how to assign variables in that menu item. My code is something like this:

ui.createMenu('foo')
  .addItem('bar', 'foobar')

function foobar(bar) {
  if (bar == 1) {
    //something
  }
  else if (bar == 2) {
    //something else
  }
}

I'm trying to assign 'bar' within '.addItem('bar', 'foobar')'

Upvotes: 2

Views: 47

Answers (1)

Lime Husky
Lime Husky

Reputation: 800

Using getActiveRange() as Parameter in Spreadsheet

Agreeing @TheMaster you cannot directly assign a parameter into the menu item, Using the getActiveRange() and getValues() method as a workaround would help.

To use this workaround, you just need to, highlight the range of the value and it returns array as the value of the parameter additionally using .toast() to check the return values of the highlighted cells.

function onOpen(e) {
  SpreadsheetApp.getUi()
    .createMenu('foo')
    .addItem('bar', 'foobar')
    .addToUi();
}

function foobar(bar = SpreadsheetApp.getActiveRange().getValues()) {
  return SpreadsheetApp.getActiveSpreadsheet().toast(bar);
}

Using Prompt

The prompt also works for passing the value by inputting it in the input text bar.

function foobar() {
  const ui = SpreadsheetApp.getUi();
  const response = ui.prompt('Parameter');
  const parameter = response.getResponseText();
  SpreadsheetApp.getActiveSpreadsheet().toast(parameter);
}

Using Prompt in Document

function onOpen(e) {
  DocumentApp.getUi()
    .createMenu('foo')
    .addItem('bar', 'foobar')
    .addToUi();
}

function foobar() {
  const ui = DocumentApp.getUi();
  const response = ui.prompt('Parameter');
  const parameter = response.getResponseText();
  console.log(parameter);
}

Reference:

Upvotes: 1

Related Questions