我有这个脚本在我的一些电子表格中完美运行但在其他电子表格上失败。
以下是代码:
function depDrop_(range, sourceRange){
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(sourceRange, true).build();
range.setDataValidation(rule);
}
function onEdit (){
var aCell = SpreadsheetApp.getActiveSheet().getActiveCell();
var aColumn = aCell.getColumn();
if (aColumn == 7 && SpreadsheetApp.getActiveSheet()){
var range = SpreadsheetApp.getActiveSheet().getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());
depDrop_(range, sourceRange);
}
else if (aColumn == 8 && SpreadsheetApp.getActiveSheet()){
var range = SpreadsheetApp.getActiveSheet().getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());
depDrop_(range, sourceRange);
}
else if (aColumn == 9 && SpreadsheetApp.getActiveSheet()){
var range = SpreadsheetApp.getActiveSheet().getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());
depDrop_(range, sourceRange);
}
}
此脚本在我的某些电子表格中运行良好,但在其他电子表格中,它会显示以下错误:
Argument cannot be null: range (line 2, file "Code")
有人可以帮我解释一下吗?
答案 0 :(得分:1)
考虑一下
行sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());
如果没有名称与aCell
内容匹配的命名区域,则sourceRange将为null,然后在尝试使用requireValueInRange(sourceRange, true)
构建验证规则时会出错。因此,在构建规则之前检查一下。还有其他更小的问题使脚本变得混乱:
&& SpreadsheetApp.getActiveSheet()
都是没有意义的。如果由于某种原因它为空,那么onEdit
函数的第一行就会出错。无论如何,当调用onEdit
触发器时,它不会为空。 这是我的版本,仅当sourceRange有效时调用depDrop_
:
function onEdit (){
var aCell = SpreadsheetApp.getActiveSheet().getActiveCell();
var aColumn = aCell.getColumn();
if (aColumn == 7 || aColumn == 8 || aColumn == 9) {
var range = SpreadsheetApp.getActiveSheet().getRange(aCell.getRow(), aColumn + 1);
if (range) {
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(aCell.getValue());
if (sourceRange) {
depDrop_(range, sourceRange);
}
}
}
}