I'm setting up a script to auto-populate a template document in Google Docs using data from Google Sheets. I keep encountering the 'TypeError: Cannot call method "getRange" of null' error. How do I resolve this error?
我正在设置一个脚本,以便使用来自Google Sheet的数据自动填充Google Docs中的模板文档。我一直遇到‘TypeError:Cannot Call Method“getRange”of Null’错误。如何解决此错误?
From what I've read, this error usually comes from not having the variable defined properly (in this case, the name of the sheet). However, I'm sure the name is the same as the file name in sheets. I've tried changing the name in both places and even making an entirely new document.
据我所知,这个错误通常是因为没有正确定义变量(在本例中是工作表的名称)。但是,我确信该名称与Sheets中的文件名相同。我试着在两个地方都改了名字,甚至制作了一个全新的文档。
4. var ss = SpreadsheetApp.openById("13YTb-lQzjijkfOKGsZRQf8fcpt_7sMy5_DX7bvlz5Yo");
5.
6. var sheet = ss.getSheetByName("SAT");
7.
8. var documentId = DriveApp.getFileById('1xrc7K9WfNiB_33y0xsB33209IZPBcpskThanC_yfzCw').makeCopy().getId();
9.
10. DriveApp.getFileById(documentId).setName('SAT Vocab ' + date);
11.
12. var body = DocumentApp.openById(documentId).getBody();
13.
14. var range = sheet.getRange("A2:A16");
This is the error message I receive:
这是我收到的错误消息:
TypeError: Cannot call method "getRange" of null. (line 14, file "Code")
This is the log from Logger.log(ss + ' ' + sheet);:
[19-06-20 12:30:52:007 CDT] undefined undefined
这是来自Logger.log(ss+‘’+Sheet)的日志;:[19-06-20 12:30:52:007 CDT]未定义未定义
更多回答
It's either not finding the spreadsheet from your openById()
or not finding the sheet with name "SAT", use Logger.log(ss + ' ' + sheet);
in your code and add the log details to the question.
如果没有从您的OpenByID()中找到电子表格,或者没有找到名为“SAT”的工作表,请在代码中使用Logger.log(ss+‘’+Sheet);并将日志详细信息添加到问题中。
优秀答案推荐
Issue:
sheet.getRange("A2:A16")
TypeError: Cannot call method "getRange" of null. (line 14, file "Code")
The error means sheet
is null
and null
doesn't have a getRange
method. Only a real Sheet
class does.
该错误意味着Sheet为空,并且Null没有getRange方法。只有真正的Sheet类才有。
As written in the documentation, There is only one reason, where the sheet
returned is null
.
正如文档中所写的,只有一个原因,即返回的工作表为空。
Returns null if there is no sheet with the given name.
There is only one answer. It's when that sheet name doesn't exist.
答案只有一个。当该图纸名称不存在时。
Possible solutions:
sheet
name refers to the tab name in a spreadsheet/workbook. It does not refer to the filename or document name. By default, the first sheet/tab is named "Sheet1". Try
工作表名称是指电子表格/工作簿中的选项卡名。它不是指文件名或文档名。默认情况下,第一张图纸/选项卡被命名为“Sheet1”。尝试
ss.getSheetByName("Sheet1");
If you still have trouble getting the sheet, check for spaces, non printable characters in the sheet name. Alternatively, Rename the sheet to something simple like S1
.
如果获取图纸仍然有问题,请检查图纸名称中是否有空格和不可打印的字符。或者,将图纸重命名为简单的名称,如s1。
更多回答
That was exactly my problem, except I had to name it ("Sheet1") rather than ("Sheet 1"). Thank you very much.
这正是我的问题,只是我不得不给它命名(“Sheet1”),而不是(“Sheet1”)。非常感谢。
我是一名优秀的程序员,十分优秀!