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