我想删除空行。第885行是非空行,应保留。但是,我的代码说(并在msgbox中显示)885为空,应该删除。当它到达i = 884时,它会打印第885行中的内容,并表示不会删除它。所以,我很困惑。它似乎正确地对数据采取行动,但它报告错误的行号。我怀疑你会告诉我偏移是零基础,行从1开始,所以如果lastrow = 888(基于1),那么我需要减去1来匹配偏移量。所以我在电子表格中看到的行885实际上是第884行作为偏移量。
但......当i =第885行有数据时,偏移量为884.当i = 884时,偏移量为883 ...所以为什么要打印第885行?在这里严重困惑。我错了什么?
最后但最重要的是......它正在删除错误的行!如何引用正确的数据,但仍然删除错误的行???
var s = SpreadsheetApp.getActiveSheet();
var range = SpreadsheetApp.getActiveSheet().getDataRange();
var i = range.getLastRow();
var msg;
var colNum;
for (; i > 1; i--) { // I like to start at the end
var foundAvalue=0; // reset flag for each row
rowRange = range.offset(i, 0, 1);
var valArray=rowRange.getValues();
var foundAvalue=0;
var msg;
var totalColumns=rowRange.getNumColumns();
colNum=0;
while (colNum < totalColumns && (foundAvalue==0)) {
if (valArray[0][colNum] != '') {
foundAvalue=1;
msg="Row " + i + " =" + valArray[0];
Browser.msgBox(msg);
msg="Row " + i + " will not be deleted";
Browser.msgBox(msg);
}
colNum++;
}
if (foundAvalue == 0) {
msg="Row " + i + " =" + valArray[0] + "WILL be deleted";
Browser.msgBox(msg);
// delete empty row
// s.deleteRow(i);
}
} // end for(i)
答案 0 :(得分:3)
下面是一些应该完成你想要的代码。你是正确的,因为问题的根源在于基于0的索引。棘手的部分是JavaScript / Apps脚本数组使用基于0的索引,但是当您调用getLastRow()
之类的内容时,返回的范围是从1开始的。总而言之,你的代码很好 - 只有这个问题才能让你沮丧。希望这会有所帮助:
function DeleteFun(){
var mySheet = SpreadsheetApp.getActiveSheet();
var range = mySheet.getDataRange();
// Iterate using a counter, starting at the last row and stopping at
// the header (assumes the header is in the first row)
for (i = mySheet.getLastRow() - 1; i > 0; i--) {
var foundAvalue = 0;
// Here we get the values for the current row and store in an array
rowRange = range.getValues()[i]
// Now we iterate through that array
for (j = 0; j <= rowRange.length; j++) {
// If any non-nulls are found, alert they won't be deleted and move on
if (rowRange[j] != null && rowRange[j] != '') {
foundAvalue = 1;
msg="Row " + (i+1) + " =" + rowRange[0] + " and will not be deleted";
Browser.msgBox(msg);
break;
}
}
if (foundAvalue == 0) {
msg="Row " + (i+1) + " =" + rowRange[0] + "WILL be deleted";
Browser.msgBox(msg);
// Delete empty row
mySheet.deleteRow(i+1);
}
}
}
答案 1 :(得分:1)
如果您不在工作表中使用公式,也可以在“纯”数组中执行此操作。
就像这样:
function deleteEmptyRows(){
var sh = SpreadsheetApp.getActiveSheet();
var data = sh.getDataRange().getValues();
var targetData = new Array();
for(n=0;n<data.length;++n){
if(data[n].join().replace(/,/g,'')!=''){ targetData.push(data[n])};// checks the whole row
Logger.log(data[n].join().replace(/,/g,''))
}
sh.getDataRange().clear(); // clear the whole sheet
sh.getRange(1,1,targetData.length,targetData[0].length).setValues(targetData);//write back all non empty rows
}