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')'
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')'
Share Improve this question edited Feb 3 at 13:04 mrC0der asked Feb 3 at 13:02 mrC0dermrC0der 254 bronze badges 3- 1 You can't pass data to functions when using a menu item. – TheMaster Commented Feb 3 at 13:48
- oh ok :( ill just use separate functions then – mrC0der Commented Feb 3 at 14:18
- Related: stackoverflow/questions/64383424 – TheMaster Commented Feb 4 at 23:49
1 Answer
Reset to default 1Using 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:
getActiveRange()
getValues()
toast()
prompt()