Add a custom menu in Google Sheets-Apps Scripts

What is Custom menu?

custom menu is a your own drop down functions list in the ribbon of your Google Sheet and you can also change it’s name. sometimes it’s hard to remember all function or formulas you made using Google Apps Scripts, so custom menu helps to work efficiently and enhance your productivity in work.

How to use functions in sheets?

when you write a function in Apps Script then question is that how to use it in your google sheets? The write syntax is use equal sign and write your function name correct as you write in the App Script.

=custom() //As you see this example no space between function name and parentheses

OnOpen trigger

To create a custom menu you have to use a OnOpen trigger which will start work whenever you open your spreadsheet. You can copy the code form Google and paste it in your spreadsheet.

function onOpen() {
  var ui = SpreadsheetApp.getUi();
                                     // Or DocumentApp, SlidesApp or FormApp.
  ui.createMenu('Custom Menu')
      .addItem('No 2', 'getvalue1') // here you just have to add your function name
      .addSeparator()
      .addSubMenu(ui.createMenu('Sub-menu')
          .addItem('No 1', 'getvalue2'))
      .addToUi();
}
function getvalue1()
{
  var value= SpreadsheetApp.getActiveSpreadsheet().getSheetByName().getRange("A2").getValue()
   return value
}
function getvalue2()
{
  var value= SpreadsheetApp.getActiveSpreadsheet().getSheetByName().getRange("A4").getValue()
   return value
}

How the above code works?

onOpen() trigger is used to runs automatically when the Google Sheets document is opened. The custom menu in Apps scripts is written in the spreadsheet UI using the SpreadsheetApp.getUi() method. it adds two items: ‘No 2‘ which calls the getvalue1() function when clicked, and ‘Sub-menu’ which contains another item labeled ‘No 1‘ calling a hypothetical function getvalue2(). Finally, addToUi() method adds the custom menu to the user interface of the spreadsheet.

Leave a Reply

Your email address will not be published. Required fields are marked *