谷歌工作表脚本编辑器删除不需要的行



我正试图使用Google Sheets脚本编辑器创建一个脚本来删除除最后10行数据外的所有数据。关闭我来的是这个代码仍然,没有成功。

function deleteUnNeededRows(startFrom)
{
var sheet = SpreadsheetApp.getActive().getSheetByName('testdoc');
// get last row index
var lastRowWithContent = sheet.getLastRow();
if(lastRowWithContent < startFrom)
{
// rows below startFrom are already blank!
return;
}

// count total number of rows to be deleted
// +1 is to include the last row
var totalRowsToBeDeleted = lastRowWithContent - startFrom + 10;

sheet.deleteRows(startFrom, totalRowsToBeDeleted); 
}

解决方案:

function deleteUnNeededRows(){  
var startFrom = 1;
var keep = 10;
var sheet = SpreadsheetApp.getActive().getSheetByName('testdoc');
var nrows = sheet.getLastRow() - startFrom - keep + 1;
if(nrows>0){
sheet.deleteRows(startFrom, nrows); 
}
}

注意getLastRow((返回最后一行内容。例如,如果您有10列,第一个10的最后一行内容为55,但工作表末尾的20列中有一个随机值,比如说900行,那么900将是工作表中的最后一行将。注意这一点,否则您将需要其他方法来获得最后一行内容。

我删除了你函数的论点。使用它是完全可以的,但您必须通过从其他地方调用它来测试这个函数。为了消除混乱,你可以这样测试它。

最新更新