getActiveSpreadsheet()始终返回null [英] getActiveSpreadsheet() always returns null
问题描述
好的,所以我正在本教程此处中了解如何设置简单的Google App脚本我被困在 18:50标记附近.进行与视频中完全相同的操作时,我收到一条错误消息.
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.
我的Code.gs文件中包含以下代码:
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);
}
和一个电子表格在另一个选项卡中打开.但是每次我尝试运行"myFunction"时,都会收到以下错误消息:
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")
因此出于某些原因,var ss = app.getActiveSpreadsheet();
会相应地返回null.当我用var ss = app.openById('MySpreadsheetIdHere');
替换该行时,它可以工作,但是硬编码id确实不是我想要的,我想使此脚本与任何打开的电子表格一起工作.
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:
- 以访客模式打开chrome,没有扩展名或其他任何内容
- 使用我的Google帐户登录到Google Drive
- 创建电子表格并保持打开状态
- 转到script.google.com并使用相同的Google帐户登录
- 创建一个新项目,然后从上方复制/粘贴代码
- 运行"myFunction" 6a.首次运行时确认权限
- 获取错误
- 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
有人看到我错过了吗?
推荐答案
您错过了 2:16 mark 创建一个有界脚本:工具>脚本编辑器...
You missed the step around 2:16 mark create a bounded script: Tools > Script editor...
这篇关于getActiveSpreadsheet()始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!