使用应用程序脚本在谷歌电子表格中设置数据验证规则时遇到问题。下面是两个函数,一个是 onChange 函数,只要用户以任何方式更改电子表格,就会触发该函数。
每当从特定工作表中添加/删除一行时,都会触发 updatenamedataVal() 函数。
一切正常,代码执行。但是单元格中没有数据验证集!怎么了?
function myonChange(e){
var ss = e.source.getActiveSheet();
var ssname = ss.getSheetName();
if((e.changeType === 'INSERT_COLUMN' || e.changeType === 'REMOVE_COLUMN') && ssname !== 'Aggregates'){
Browser.msgBox('Whoops!','You are not allowed to add/remove columns. Please undo action by pressing CTRL+Z', Browser.Buttons.OK);
}
else if((e.changeType === 'INSERT_ROW' || e.changeType === 'REMOVE_ROW') && ssname === 'Teacher Details'){
var ssrange = ss.getDataRange();
var valrange = ss.getRange(2,3,ssrange.getLastRow(),1);
updatenamecelldataVal(valrange);
}
};
function updatenamecelldataVal(valrange){
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var numsheets = SpreadsheetApp.getActiveSpreadsheet().getNumSheets();
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(valrange).build();
for(var i = 0; i < numsheets; i++){
var sheetname = sheets[i].getName();
var sheetrange = sheets[i].getDataRange();
var sheetlastrow = sheetrange.getLastRow();
if(sheetname !== 'Teacher Details' && sheetname !== 'Aggregates' && sheetname !== 'List of Subjects'){
for(var j = 0; j < (sheetlastrow/17); j++){
var namecell = sheetrange.getCell(4+(17*j), 2);
namecell.clearDataValidations();
namecell.setDataValidation(rule);
}
}
}
};