Creating add ons in Google Apps Script

↘锁芯ラ 提交于 2021-02-11 16:40:18

问题


I have put together some code which I would like to access in other Google sheets, however, as it uses SpreadsheetApp.getUi the code has to be bound to a sheet. I have therefore decided to create the code as an add on.

Unfortunately, the add ons don't appear in other spreadsheets and disappear from the spreadsheet where the add on was created unless I open up the apps script page. Where am I going wrong?

var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();

function onOpen(e) {
  SpreadsheetApp.getUi().createAddonMenu()
  .addItem("Delete Columns", "delCols")
  .addItem("Insert Columns", "insCols")
  .addItem("Subjects Sheet", "deptNamesKS4")
  .addItem("Subjects Sheet", "deptNamesKS3")
  .addToUi();

};

function onInstall(e) {
  onOpen(e);
};

function delCols(e) {

  var lastColumn = ss.getLastColumn();
  var headers = ss.getRange('1:1').getValues();

  var searchVal = ui.prompt("Enter name of column to be deleted").getResponseText()

  var names = headers[0];
  var loopCounter = names.length - 1

  for (var i = loopCounter; i >= 1; i--) {
    if(names[i].indexOf(searchVal) > -1) {
      ss.deleteColumn(i + 1);
    }DE
  }
}

function insCols(e) {

  var lastColumn = ss.getLastColumn();
  var headers = ss.getRange('1:1').getValues();

  var searchVal = ui.prompt("Enter name of column to be deleted").getResponseText();
  var noCols = ui.prompt("Number of columns to be inserted").getResponseText();

  var names = headers[0];
  var loopCounter = names.length - 1

  for (var i = loopCounter; i >= 1; i--) {
    if(names[i].indexOf(searchVal) > -1) {
      ss.insertColumnsBefore(i + 1, noCols);
    }
  }
}

Any help would be appreciated.

Thanks


回答1:


In order to use the add-on in other files, you would have to do one of the following:

(1) Publish the add-on, as explained here.

(2) Test the add-on via Run > Test as add-on.... I wouldn't recommend this, since you would have to add each file you want to use the add-on with first, and open the file from there.

Workaround (use a library):

A possible workaround to reach your purpose would be, considering what you want the add-on for, instead of using your code as an add-on, save it in a library and then include it in each file you want it to run (you would have to change createAddonMenu to createMenu).



来源:https://stackoverflow.com/questions/59661799/creating-add-ons-in-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!