2

What is the difference between these two ways of getting the same thing (a new menu item)?

Version 1

 function onOpen(e) {
   SpreadsheetApp.getUi()
       .createMenu('My Menu')
       .addItem('My Menu Item', 'myFunction')
       .addSeparator()
       .addSubMenu(SpreadsheetApp.getUi().createMenu('My Submenu')
           .addItem('One Submenu Item', 'mySecondFunction')
           .addItem('Another Submenu Item', 'myThirdFunction'))
       .addToUi();
 }

Version 2

function onOpen() {
  var menu = [{name: "My Menu Item", functionName: "myFunction"}]
  SpreadsheetApp.getActiveSpreadsheet().addMenu("My Menu", menu);
}

2 Answers 2

3

addMenu

This is a method of Spreadsheet class, i.e., it only applies to spreadsheets. All it does is add a new menu item with second-level submenus. On the upside, the syntax is very simple.

getUi

This method is currently available for three apps: SpreadsheetApp, DocumentApp, and FormApp. It returns an instance of user interface which can be used for more than just adding a menu item. One can show alerts, prompts, dialogs, and even add an interactive sidebar with custom content. Also, the menu creating options are richer: they allow separators and nested submenus. There are special add-on menus, too. Accordingly, the syntax is more verbose.

Conclusion

Neither of two methods is deprecated; use whichever fits your goal better.

-1

Another difference: you cannot add submenus (child menu items under parent menu items) with addMenu. This limitation pretty much self-deprecates the addMenu method despite the cool syntax.

2
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 29, 2023 at 19:38
  • 1
    This answer should be edited to clarify the "difference" from @user79865's answer You state "you cannot add submenus" yet the other answer indicates that you can add a "new menu item" (parent) with "second-level submenus" seems like a contradiction or one or both of the answers are unclear.
    – Blindspots
    Jun 29, 2023 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.