Google Apps Script is a powerful tool that allows users to extend and automate Google Workspace applications like Sheets, Docs, and Forms. One of its useful features is the ability to create custom menus that enhance the functionality of these apps. In this guide, you will learn how to create a custom menu in Google Sheets using Google Apps Script.
function onOpen() {
// Create a custom menu
const ui = SpreadsheetApp.getUi();
ui.createMenu('My Custom Menu')
.addItem('Say Hello', 'sayHello') // Adds a menu item
.addSeparator() // Adds a separator line
.addItem('Show Alert', 'showAlert') // Adds another menu item
.addToUi(); // Displays the menu in the Google Sheet
}
function sayHello() {
SpreadsheetApp.getActiveSpreadsheet().toast('Hello, World!', 'Greeting');
}
function showAlert() {
const ui = SpreadsheetApp.getUi();
ui.alert('This is an alert from your custom menu!');
}
- The
onOpen
function runs automatically when the spreadsheet is opened. It creates a custom menu called My Custom Menu. - The
sayHello
function displays a toast message at the bottom-right corner of the screen. - The
showAlert
function shows a popup alert message.
- Click Review Permissions.
- Choose your Google account.
- Click Advanced > Go to [Project Name] (unsafe).
- Click Allow.
4. Refresh the Google Sheet, and you should see a new menu called My Custom Menu in the menu
bar.
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('My Custom Menu')
.addItem('Say Hello', 'sayHello')
.addSubMenu(
ui.createMenu('Submenu')
.addItem('Submenu Item 1', 'submenuItem1')
.addItem('Submenu Item 2', 'submenuItem2')
)
.addToUi();
}
function submenuItem1() {
SpreadsheetApp.getActiveSpreadsheet().toast('This is Submenu Item 1');
}
function submenuItem2() {
SpreadsheetApp.getActiveSpreadsheet().toast('This is Submenu Item 2');
}
- Test your script thoroughly to ensure it works as expected.
- Keep your code organized and use meaningful names for your menu items and functions.
- Share your Google Sheet with others, and they can use your custom menu after accepting script permissions.
With these steps, you can create custom menus in Google Sheets to streamline tasks and enhance productivity.