问题
Okay, so I was following this tutorial here about how to set up a simple Google App Script and I was stuck at around the 18:50 mark. I was getting an error message while doning the exact same thing as in the video.
I have this code in my Code.gs file:
function myFunction() {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();
activeSheet.getRange("D2").setValue(99);
}
and a spreadsheet open in another tab. But everytime I try to run "myFunction" I get the following error message:
TypeError: Cannot call method "getActiveSheet" of null. (line 5, file "Code")
So for some reason var ss = app.getActiveSpreadsheet(); apperently returns null. It works when I replace that line with var ss = app.openById('MySpreadsheetIdHere');, but hard coding the id is really not what I want, I'd like to make this script work with any arbitrary opened spreadsheet.
Running the code via Run > Test as add-on doesn't work either.
From a similar question I gathered that it seems to be hard to reproduce this problem, here's exact steps to reproduce:
- open up chrome in guest mode, no extensions or anything
- sign in to google drive with my google account
- create a spreadsheet and keep it open
- go to script.google.com and sign in with that same google account
- create a new project and copy/paste the code from above
- run "myFunction" 6a. confirm permissions when running it for the first time
- get the error
Anyone see what I missed?
回答1:
You missed the step around 2:16 mark create a bounded script: Tools > Script editor...
来源:https://stackoverflow.com/questions/50105012/getactivespreadsheet-always-returns-null