我创建了这个脚本,它使一个表单发布了一个模糊,我希望它被提交到电子表格,但我不断收到此错误Exception: incorrect range width, was 3 but should be 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;
}
}
答案 0 :(得分:6)
如果您的二维数组没有100%四边形设置并且与所选范围不匹配,则会发生此错误。
例如,如果你有一个数组:
[
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,g],
[a,b,c,d,e,f]
]
它会给你一个错误Exception: incorrect range width, was 7 but should be 6
当然,解决方案是用空值填充多余的单元格:
[
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,g],
[a,b,c,d,e,f,''],
]
基本上,确保它们都不比任何其他阵列长。
答案 1 :(得分:4)
您已选择具有起始位置(行,列)但没有指定高度(行)或宽度(列)的范围。默认为1 x 1.然后,setValues方法尝试应用二维数组,该数组是一组不同的维度,在此示例中为1行x 2列:
sheet.getRange(sheet.getLastRow()+1, 1).setValues([[ title, post]]);
-------------------- - ----------------
| +- column |
+- row +- 1 row, 2 columns
当异常报告width
时,将其与列等同,而不是行。
您应该使用.getRange(row, column, numRows, numColumns)
,如:
sheet.getRange(sheet.getLastRow()+1, 1, 1, 2).setValues([[ title, post]]);
为了改善维护,请尽量避免使用神奇的数字。
var outData = [[ postTitle, title, post ]];
sheet.getRange(sheet.getLastRow()+1, 1, outData.length, outData[0].length)
.setValues(outData);
这样,如果您更改要存储到工作表中的数据,则不需要维护将其写出的行。相反,它将根据数据维度计算正确的维度。
最后一句话:摆脱那个try..catch
阻止,你不需要它,它会导致错误,例如意外地将你的return app
包括在catch块中,可能导致你的应用程序无声地失败。