Google apps script 使用应用程序脚本将表单提交到电子表格时出错
我创建了这个脚本,它制作了一个表单来发布一个简介,我希望它被提交到电子表格,但我一直收到这个错误Google apps script 使用应用程序脚本将表单提交到电子表格时出错,google-apps-script,google-sheets,google-forms,Google Apps Script,Google Sheets,Google Forms,我创建了这个脚本,它制作了一个表单来发布一个简介,我希望它被提交到电子表格,但我一直收到这个错误异常:不正确的范围宽度,是3,但应该是5无论我如何更改getRange中的行数,这个错误中的数字总是相同的。有没有什么方法可以更新我不知道的代码?每次更改代码时,我都会部署它 function doGet() { var app = UiApp.createApplication().setTitle('Form for news update'); //panel for form
异常:不正确的范围宽度,是3,但应该是5
无论我如何更改getRange中的行数,这个错误中的数字总是相同的。有没有什么方法可以更新我不知道的代码?每次更改代码时,我都会部署它
function doGet() {
var app = UiApp.createApplication().setTitle('Form for news update');
//panel for form
var panel = app.createVerticalPanel().setId('panel');
//elements for the form
var postTitle = app.createLabel('Title');
var title = app.createTextBox().setId('title');
var postLabel = app.createLabel('new post:');
var post = app.createTextArea().setId('post');
var btn = app.createButton('Submit');
//handler to execute posting by click the button
var handler = app.createServerClickHandler('Submit');
handler.addCallbackElement(panel);
//add this handler to the button
btn.addClickHandler(handler);
//add the elements to the panel
panel.add(postTitle)
.add(title)
.add(postLabel)
.add(post)
.add(btn);
//add the panel to the app
app.add(panel);
return app;
}
function Submit(e){
//get the app and send it to the spreadsheet
var app = UiApp.getActiveApplication();
try{
//get the post
var postTitle = e.parameter.postTitle;
var title = e.parameter.title;
var post = e.parameter.post;
//put the info into a spreadsheet
var ss = SpreadsheetApp.openById('KEY IN HERE REMOVED FOR PRIVACY');
var sheet = ss.getSheets()[0];
sheet.getRange(sheet.getLastRow()+1, 1).setValues([[ title, post]]);
}catch(e){
app.add(app.createLabel('Error occured:'+e));
return app;
}
}
您选择的范围具有起始位置(行、列),但没有指定高度(行)或宽度(列)。它将默认为1 x 1。然后,setValues方法尝试应用一个二维数组,该数组是一组不同的维度,在本例中为1行x 2列:
sheet.getRange(sheet.getLastRow()+1, 1).setValues([[ title, post]]);
-------------------- - ----------------
| +- column |
+- row +- 1 row, 2 columns
当异常报告宽度时,请将其与列而不是行等同
您应该使用,如中所示:
为了改进维护,尽量避免使用神奇的数字
var outData = [[ postTitle, title, post ]];
sheet.getRange(sheet.getLastRow()+1, 1, outData.length, outData[0].length)
.setValues(outData);
这样,如果更改要存储到工作表中的数据,则不需要维护将其写出的行。相反,它将根据数据维度计算正确的维度
最后一句话:摆脱
try..catch
块,你不需要它,它会导致错误,比如意外地将你的return应用程序包含在catch块中,可能导致应用程序以静默方式失败。如果二维数组没有100%四边形设置,并且与选定范围不匹配,则也会发生此错误
例如,如果您有一个数组:
[
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,g],
[a,b,c,d,e,f]
]
它会给您一个错误,告诉您异常:范围宽度不正确,为7,但应为6
当然,解决方案是用空值填充多余的单元格:
[
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,''],
]
基本上,确保它们都不比任何其他阵列长。非常感谢您的反馈,信息量非常大!你能推荐一些好的读物吗?我应该用什么来代替try..catch?抱歉,我昨天才开始使用应用程序脚本。首先学习Javascript很有帮助,没有像jQuery这样的web技术。例如,从Codeacademy在线学习。各种教程都很有帮助。我在这里通过回答问题学到的东西比我自己用煤气学到的要多,所以我建议你尝试一下,即使只是作为练习。请参见中的“我的笔记”。仅在您无法预料或以其他方式处理的错误时使用它。
[
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,''],
]