簡體   English   中英

您無法刪除工作表 Google Sheets Script 上的所有行

[英]You can't delete all the rows on the sheet Google Sheets Script

我正在嘗試使用以下代碼從整個工作簿中刪除空單元格:

//Remove All Empty Rows in the Entire Workbook
function removeEmptyRows() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();
for (var s in allsheets){
var sheet=allsheets[s]
var maxRows = sheet.getMaxRows(); 
var lastRow = sheet.getLastRow();
if (maxRows-lastRow != 0){
  sheet.deleteRows(lastRow+1, maxRows-lastRow);
    }
  }
}

來自這篇文章: 刪除 Google 電子表格中的所有空行

問題是我不斷收到此錯誤:“異常:您無法刪除工作表上的所有行。”

工作簿有多個工作表,所有工作表都至少在前 20 行中包含數據。

需要此腳本的原因是由於此錯誤而無法運行導入腳本的更大問題:“異常:此操作會將工作簿中的單元格數量增加到 5000000 個單元格的限制以上。”

任何幫助將不勝感激! 謝謝

您的函數似乎可以執行您想要的操作,如果工作表完全為空,我只會收到該錯誤。 一種處理方法是向 IF 添加條件以查看工作表中是否有任何內容:

function removeEmptyRows() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();
  for (var s in allsheets) {
    var sheet = allsheets[s]
    var maxRows = sheet.getMaxRows();
    var lastRow = sheet.getLastRow();
    if (lastRow > 0 && maxRows - lastRow != 0) {
      sheet.deleteRows(lastRow + 1, maxRows - lastRow);
    }
  }
}

如果您只需要清理所有內容,則可以通過以下方式更快、更短地完成:

function removeAllRows() {
  SpreadsheetApp.getActive().getSheets().forEach(s => s.clear());
}

如果您需要保持格式,您可以使用clearContents()而不是clear()


以防萬一,如果您需要刪除所有行(並保留非行),那么不使用deleteRows()可能是有意義的,因為它很慢。 您可以從工作表中獲取作為二維數組的值,從二維數組中刪除“行”,然后將其值重新設置在工作表上。 可以這樣做:

function removeEmptyRows() {

  // function to remove all empty lines from a 2D array
  const get_not_empty_rows = (data) => data.filter(row => row.filter(String) != '');

  // function to get a range on the given sheet by the size of a given 2D array
  const get_new_data_range = (s, data) => s.getRange(1, 1, data.length, data[0].length);

  var sheets = SpreadsheetApp.getActive().getSheets();

  for (let sheet of sheets) {                          // for every sheet
    let all_rows = sheet.getDataRange().getValues();   // get 2D array
    let not_empty_rows = get_not_empty_rows(all_rows); // remove empty lines
    if (not_empty_rows.length > 0) {                   // if there are lines
      sheet.getDataRange().clearContent();             // clean the sheet
      get_new_data_range(sheet, not_empty_rows).setValues(not_empty_rows); // set the values
    }
  }
  
}

但是您需要決定是否刪除工作表上的格式。 其余行的deleteRows()格式保持不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM