问题描述
我的Google App脚本将循环遍历所有WorkSheets以查找特定的字符串,并输出在其上找到的行和列,但是一旦我添加新的空WorkSheet,我就会收到错误消息“异常:列数范围必须至少为1。”我想对造成此问题的原因提供一些意见。谢谢。
function doForAllSheets(){
var spreadsheet = SpreadsheetApp.getActive();
var allSheets = spreadsheet.getSheets();
allSheets.forEach(function(sheet){
if(sheet.getSheetName() !== "Main"){
sheet.activate();
findValueInRange();
}
})
}
function findValueInRange () {
var ss = SpreadsheetApp.getActiveSheet(),theLastColumn = ss.getLastColumn(),theLastRow = ss.getMaxRows();
//Returns a two dimensional array of both rows and columns
var values = ss.getRange(1,1,theLastRow,theLastColumn).getValues();
var i=0,rownum=0,thisRow,colvalue,whatToFind = "testserial",j=0;
for(i=0;i<values.length;i++) {
thisRow = values[i];
for (j=1;j<thisRow.length;j++) {
colvalue = thisRow[j];
if (colvalue === whatToFind) {
Logger.log("The string is in row: " + (i + 1) + " and column: " + (j+1));
}
}
}
}
解决方法
像这样重写函数:
function findValueInRange () {
var ss = SpreadsheetApp.getActiveSheet(),theLastColumn = ss.getLastColumn(),theLastRow = ss.getMaxRows();
if( theLastColumn>0) {
//Returns a two dimensional array of both rows and columns
var values = ss.getRange(1,1,theLastRow,theLastColumn).getValues();
var i=0,rownum=0,thisRow,colvalue,whatToFind = "testserial",j=0;
for(i=0;i<values.length;i++) {
thisRow = values[i];
for (j=1;j<thisRow.length;j++) {
colvalue = thisRow[j];
if (colvalue === whatToFind) {
Logger.log("The string is in row: " + (i + 1) + " and column: " + (j+1));
}
}
}
}
}