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