Oliver84
Oliver84

Reputation: 307

Conditionally move row from one sheet to another sheet

I'm trying to move a row from Sheet1 to Sheet2 if a certain value in Sheet1 is true. For example:

If B12=8/12/2012 in Sheet1, then copy row 12 from Sheet1 to Sheet2 by adding a new row under row 15 (which would be a named range) and then deleting the original row 12 from Sheet1.

Is this possible?

Upvotes: 3

Views: 1372

Answers (1)

Joachin Joseph
Joachin Joseph

Reputation: 343

Hope This will work out...

function copyRowtoDiffSheet(){
var ss = SpreadsheetApp.getActiveSpreadsheet();

 var sheet1 = ss.getSheetByName('Sheet1');
 var sheet2 = ss.getSheetByName('Sheet2');

 var cell = sheet1.getRange("B12").getCell(1, 1);//Get the B12 cell from sheet1
 var rowtoInsert = "15"; //Enter in which row you want to insert in sheet2

 if(cell.getValue() == "compareString") //compare cell.getValue() =="8/12/2012" 
 {

  sheet2.insertRows(rowtoInsert); //Insert a empty row in sheet2 at R15, It will be doing insert before operation. Successive rows will be moved below.
  var range2 = sheet2.getRange(rowtoInsert ,1,1,sheet1.getLastColumn()); // Select sheet2 row15 as a range
  sheet1.getRange(cell.getRow(),1, 1, sheet1.getLastColumn()).copyTo(range2); // copy the selected sheet1 range into sheet2 range
  sheet1.deleteRow(cell.getRow()); //delete the R15 in sheet1
 }
}

Upvotes: 1

Related Questions