Search code examples
javascriptgoogle-apps-scriptgoogle-sheetssyntax-errorgoogle-sheets-query

Unable to add a custom menu to Google Sheets



I'm having trouble creating a custom menu. The custom function works as intended. I can see that in the sheet so it's not a permission issue. Can somebody please adivse?

Thank you :)

P.S I have tried adding only a menu without a button inside to check if the problem was with how I was adding the function name. That didn't work either.
function addRowTotal() 
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("sheet1");
  var lastRow= sheet.getLastRow()-1;
  var data = sheet.getRange(2,1,lastRow,3).getValues();

  var totalsArray=[];
  data.forEach(function(row)
               {
    var name= row[0];
    var price= row[1];
    var qty = row[2];
    var tot=price*qty;
    var doz=price*12;
    row.push(tot,doz);
    //Logger.log (data);
    totalsArray.push([tot,doz]); 
    Logger.log(totalsArray);
               })
  sheet.getRange(2,4,lastRow,2).setValues(totalsArray);
}

function OnOpen()
{
 var ui = SpreadsheetApp.getUi(); 
 ui.createMenu("Custom Menu")
 .addItem("Row totals","addRowTotal")
 .addToUi;
}

Solution

  • You are very close besides the two following things:

    1. you made a typo: OnOpen should be onOpen,
    2. you forgot to add the parentheses: addToUi should be addToUi().

    Try this instead:

    function onOpen()
    {
     var ui = SpreadsheetApp.getUi(); 
     ui.createMenu("Custom Menu")
     .addItem("Row totals","addRowTotal")
     .addToUi();
    }