如何处理在使用 SpreadsheetApp.openById() 时引发的异常



我对任何类型的编码和搜索都很陌生,因为我可能无法找到此异常的解决方案:

异常:在对象电子表格应用程序上获取方法或属性 openById 时出现意外错误。(第 16 行(

我编写的脚本从文件 ID 列表中复制每个文件,将整个内容作为值粘贴到复制的文件中。

我已经做的是检查我的appscript.json中的oauthScope是否需要授权,我认为我已经给予了足够的授权(电子表格和驱动器(。我没有收到任何其他权限提示。

任何帮助或建议都会很棒(通常对于我写的内容,但重要的是例外(

这是脚本:

function copyPasteValues()
{
//Define destination archive folder
var Destination = DriveApp.getFolderById("ID");
//Open correct sheet in the Archiving Center file and get ID range
var AllFileID_ss = SpreadsheetApp.openById("ID_2"); *------- no error on this one*
var AllFileID_sheet = AllFileID_ss.getSheetByName("Sheets_to_be_archived");
var FileID = AllFileID_sheet.getRange("B2:B10").getValues();
//Select the correct file to archive and create a copy
for (var i=0; i<FileID.length;i++)
{
if (FileID != "-")
{
var archfile = SpreadsheetApp.openById(FileID[i]); *------------ exception being thrown here (line 16)*
var archcopy = DriveApp.getFileById(FileID[i]).makeCopy("Archive "+archfile.getName(), Destination);
var copyId = archcopy.getId();
var sheetNumber = archfile.getSheets().length;
//Select correct sheets in copy, and paste values
for (var j=0; j<sheetNumber;j++)
{
var values = archfile.getSheets()[j].getDataRange().getValues();
SpreadsheetApp.openById(copyId).getSheets()[j].getRange(archfile.getSheets()[j].getDataRange().getA1Notation()).setValues(values);
}    
}
}
Browser.msgBox("Archiving is done");
}

附言否则,脚本运行良好,尽管有异常,仍执行复制和存档,但最后一行是msgBox不显示消息。我不知道为什么。

根据文档,openById(id)方法签名需要一个字符串作为参数。您的FileID变量包含由getValues()方法调用返回的值数组数组(请参阅文档(,因此通过索引从中访问项目[i]返回一个数组,而不是值。

条件FileID != "-"始终在脚本中评估为true,因为您正在进行严格的比较,以检查案例中的不等式。一旦发生类型不匹配,它就会返回true"object" !== "string"

const whatGetValuesReturns = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
];
const whatOpenByIdExpects = "string";
for(var i = 0; i < whatGetValuesReturns.length; i++) {
const whatEachIterationOfLoopGets = whatGetValuesReturns[i];

const typeOfWhatIsExtracted = typeof whatEachIterationOfLoopGets;

console.log(
`Expected ${whatOpenByIdExpects}, 
got ${typeOfWhatIsExtracted} with values:
${whatEachIterationOfLoopGets.join(" ")}`
);

}


基于讨论,我需要澄清一下,当您将getRange()限制为单个列(off-note:B:B将是列引用,B2:B10是一系列单元格(时,它仍然返回一个Range实例,该实例又定义了始终返回值矩阵的getValues()方法:

const singleColumn = [
[1],
[2],
[3],
[4]
];
for(const row of singleColumn) {
const value = row[0]; //<-- since we have only one, first index is used
console.log(value);
}

正如你@Oleg Valter正确指出的那样,我试图将我认为是一个字符串值,但实际上是一个数组,传递到openbyID(id(中。您在下面的评论澄清了这一点。

我看到你有一个假设,将范围限制为一列只会让你得到一列,但这不是程序的工作方式——它们非常愚蠢。你告诉脚本给你一个列表行,其中每一行都是一个只有一个项目的列表(数组(,这就是它返回的内容

我修改了脚本的这一部分,如下所示,它起作用了:

var AllFileID = AllFileID_sheet.getRange("B2:B10").getValues();
//Select the correct file to archive and create a copy
for (var i=0; i<AllFileID.length;i++)
{
var FileID = AllFileID[i][0] *----this is the change to pick out the value from the array*
if (FileID != "-")
{
var archfile = SpreadsheetApp.openById(FileID); *---works!*

非常感谢!

最新更新