简体   繁体   中英

I need help to Copy and Paste certain cells in a row to another sheet if criteria is met

I only wanted to copy column A, B,C, and G and on my sample sheet . I wanted it to be transferred to sheet 1 then delete the row from sheet2.

So basically what I wanted is this to happen and after that delete the row on sheet2.

"column A" ---> "column A"  
"column B" ---> "column B"  
"column C" ---> "column D"  
"column G" ---> "column C"

My current script copies the whole row and I'm not sure how to make it work as I have mentioned above. I can't use query function, since sheet 1 is automatically being populated.

function onEdit(event) {
 // assumes source data in sheet named main
 // target sheet of move to named Completed
 // getColumn with drop-downs is currently set to column 3 or C
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var s = event.source.getActiveSheet();
 var r = event.source.getActiveRange();

 if(s.getName() == "Sheet2" && r.getColumn() == 8 && r.getValue() == "Done") {
   var row = r.getRow();
   var numColumns = s.getLastColumn();
   var targetSheet = ss.getSheetByName("URL Checklist Raw");
   var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
   s.getRange(row, 1, 1, numColumns).moveTo(target);
   s.deleteRow(row);
 } 
}



This can be done easily by using the getValues() method of the Range class. The idea is that the values of the range are fetched, re-ordered, and then set to the destination values. You can see below a modified version of the original code that accomplishes what you describe.

Additionally, instead of getting the target range and setting the values to it, you can simply use the appendRow() method, which allows for more concise code:

function onEdit(event) {
 // assumes source data in sheet named main
 // target sheet of move to named Completed
 // getColumn with drop-downs is currently set to column 3 or C
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var s = event.source.getActiveSheet();
 var r = event.source.getActiveRange();

 if(s.getName() == "Sheet2" && r.getColumn() == 8 && r.getValue() == "Done") {
   var row = r.getRow();
   var targetSheet = ss.getSheetByName("Sheet1");
   var values = s.getRange(row, 1, 1, 7).getValues()[0];
   var resultRow = [values[0], values[1], values[6], values[2]];
   targetSheet.appendRow(resultRow);
   s.deleteRow(row);
 } 
}

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