问题
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.
- Go to the
Insert > Drawing
menu item and create a shape; any shape will do, this will act as your button. - Press
Save and Close
to add this to your sheet. - 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 clickAssign script
. - In the new window, type
getStatusCode
and pressOK
.
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