To add a custom menu UI in Google Apps Script, you can use the addMenu(name, subMenus)
method of the Ui
class. Here is an example of how to add a custom menu UI in Google Sheets:
function onOpen() {
var ui = SpreadsheetApp.getUi();
var menu = ui.createMenu('My Custom Menu');
menu.addItem('Menu Item 1', 'menuItem1');
menu.addItem('Menu Item 2', 'menuItem2');
menu.addSeparator();
menu.addSubMenu(ui.createMenu('Sub Menu')
.addItem('Sub Menu Item 1', 'subMenuItem1')
.addItem('Sub Menu Item 2', 'subMenuItem2'));
menu.addToUi();
}
function menuItem1() {
// Add your code here for the action of menu item 1
}
function menuItem2() {
// Add your code here for the action of menu item 2
}
function subMenuItem1() {
// Add your code here for the action of sub menu item 1
}
function subMenuItem2() {
// Add your code here for the action of sub menu item 2
}
In this example, the onOpen
function is called automatically when the Google Sheet is opened. It creates a new menu with the name “My Custom Menu” and adds two menu items (Menu Item 1
and Menu Item 2
) and a sub-menu (Sub Menu
) with two sub-menu items (Sub Menu Item 1
and Sub Menu Item 2
). The menuItem1
, menuItem2
, subMenuItem1
, and subMenuItem2
functions are called when the corresponding menu items are clicked, and you can add your own code in these functions to perform specific actions.
Once you have saved and executed the script, the custom menu will be available in your Google Sheet, and you can click on it to access the menu items and sub-menu items.
