Run script only on click on button instead with open the sheets

本秂侑毒 提交于 2020-06-28 03:56:21

问题


Currently the following script runs with opening the Google Sheet table. I want to have that the script should only run with a click of a button. How can I do that?

function getStatusCode(url){
   var options = {
     'muteHttpExceptions': true,
     'followRedirects': false
   };
   var url_trimmed = url.trim() || "";
   var response = UrlFetchApp.fetch(url_trimmed, options);
   return response.getResponseCode();
}

回答1:


Answer:

Rather than using the =IFERROR* formula, you can make the function set the value for your cell rather than return.

Code:

Make sure to change the range of cells containing your URLs and the range of cells that have =IFERROR() forumae in. In this example script they are in column G and H respectively.

function getStatusCode(){
  var options = {
    'muteHttpExceptions': true,
    'followRedirects': false
  };
  // this is the range of cells containing your WENNFEHLER foruma
  var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("H1:H100");
  
  // this is the range of urls
  var range2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("G1:G100");
  
  var newValues = [];
  for (var i = 0; i < range.getValues().length; i++) {
    var url_trimmed = range2.getValues()[i][0].trim() || "";    
    try {
      var response = UrlFetchApp.fetch(url_trimmed, options);
      newValues.push([response.getResponseCode()]);
    }
    catch(e) {
      newValues.push(["Not found"]);
    }
  }
  range.setValues(newValues);  
}

Assigning to a Button:

Now, you can create an in-sheet button which will run the script whenever you click it.

  1. Go to the Insert > Drawing menu item and create a shape; any shape will do, this will act as your button.
  2. Press Save and Close to add this to your sheet.
  3. Move the newly-added drawing to where you would like. In the top-right of the drawing, you will see the vertical ellipsis menu (). Click this, and then click Assign script.
  4. In the new window, type getStatusCode and press OK.

Now, each time you click the button, the script will run. As it sets the cell value rather than being called from a formula, it will no longer run on opening the Sheet.

I hope this is helpful to you!

* Translation note: WENNFEHLER means IFERROR



来源:https://stackoverflow.com/questions/60947799/run-script-only-on-click-on-button-instead-with-open-the-sheets

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