Sunday, March 2, 2014

Deleting rows of data using Google Script

I'm building a basic contacts database inside of a Google Spreadsheet, primarily as a way to learn Javascript. So far I've looked at passing the data in my spreadsheet into an array for manipulation and then how to do this with a dynamically changing data range in my spreadsheet. This post explores the code needed to delete rows of data in the spreadsheet. After this we'll look at adding rows of data using a GUI, then adding a way to search for a contact and display the data for that contact. That'll form the basis of my small program, and I can build out from there.

Deleting a row of data with Google script is pretty easy - there's a "deleteRow()" method that we call on to achieve this. I want to give the user a choice of which row to delete (using an input box) and then check that the user enters a valid row number before executing the delete row method.
  • So, step 1 is to determine how many rows are in the spreadsheet, let's call it N.
  • Step 2 is to ask the user to choose a row to delete between 1 and N, using an input box.
  • Step 3 is to check the user has entered a valid number between 1 and N before executing the deleteRow command. This is achieved with a do-while loop. The loop keeps looping until the entry in the user box is a number between 1 and N.
  • Step 4 is to delete the row chosen by the user in Step 3, using the deleteRow() method.
  • That's it!

The code to achieve is as follows:


function deleteRow() {
  // select spreadsheet and sheet
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheets()[1];
  
  // get the size of the data range
  var N = sheet.getLastRow();
  var numString = "Choose row to delete between 1 and " + N;
  
  var isNum = false;
  
  // here is the awesome do-while loop!
  // it runs through the loop once, then checks status of isNum
  // while isNum is still false then it loops again
  // if user has entered a number between 1 and N then
  // set isNum to true
  // when isNum is true, we exit the loop. Magic!
  do {
    var delNum = Browser.inputBox(numString);
      if (delNum > 0 && delNum <= N) {
        isNum = true;
      }
  } while (isNum == false);
  
  sheet.deleteRow(delNum);  
}

No comments:

Post a Comment