简体   繁体   中英

Trying make a macro to delete last number of rows and columns in google sheets

i am using this script to delete last rows and columns in the current google sheet tab, and it gives me "Those rows are out of bounds." error. i dont know why , and it works fine when i use integers instead of the 2nd parameter .

var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();

//Delete rows 201+
sheet.deleteRows(201, sheet.getLastRow() - 200 );

//Delete Columns 10+
sheet.deleteColumns(10, sheet.getLastColumn() - 9 );

An out of bounds error relates to the methods .deleteRows and .deleteColumns. The error arises from trying to call a range that doesn't exist. Whether it's because it is trying to call over the maximum number of cells in your sheet, or under it by trying to call a 0th range or even a negative range. You can't call .getRange(0,0) because it doesn't exist and will return your out of range error. The problem here is I am.unable to give you the solution since I don't have the context of how you are getting some of your variables. What I can do is suggest using a different method. Judging by your code you only want to delete ONE row and ONE column. This is much easier done with .deleteRow(Row) @nd .deleteColumn(Column) Here is the documentation: https://developers.google.com/apps-script/reference/spreadsheet/sheet#deleteColumn(Integer) And https://developers.google.com/apps-script/reference/spreadsheet/sheet#deleteRow(Integer) If this doesn't help you create a copy of your sheet, remove any sensitive information and share the link with edit permissions so I may look over your code and spreadsheet myself for better context on your problem.

Here's a couple of simple scripts that might help you.

function delLastNRows(n){
  var n=n || 3;//allows you to delete last three rows without passing function a parameter.
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var lr=sh.getLastRow();
  if(lr>=n){
    for(var i=0;i<n;i++){
      sh.deleteRow(sh.getLastRow());
    }
  }
}

function delLastNCols(n){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var lc=sh.getLastColumn();
  if(lc>=n){
    for(var i=0;i<n;i++){
      sh.deleteColumn(sh.getLastColumn())
    }
  }
}

i found out the answer guys, i should use getMaxRows() to get total number of rows in the sheet and here is the function i used.

function delRows51() {
  var ss = SpreadsheetApp.getActiveSheet();
  ss.deleteRows(51, ss.getMaxRows() - 50);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM