Home > Software engineering >  Copy row data based on cell value to new sheet in Google Sheets
Copy row data based on cell value to new sheet in Google Sheets

Time:08-03

I would like to make an Apps Script to allow a row of data to be copied to another sheet for "history".

I have tried several different scripts. While some have sort of worked, ultimately, they quit functioning for some reason. Also, they did not have the completeness I wanted.

I want a checkbox to be selected and then a selection made from the custom UI button. Upon clicking the Copy Data button, the row data that contains the checkbox, needs to be copied to the new sheet. After the data is copied, I would like a function to delete the row(s), but not formulas, that have a checkmark in them. This would preferably be made as another button in the custom UI menu.

Column A holds employee names. Column B autofills current date when Column A sees input from dropdown. Column C holds the checkbox. Column D is generic work list.

Is something like the following what I need?

function onOpen(e) {
  let ui = SpreadsheetApp.getUi();
  ui.createMenu('PAS Data')
    .addItem('Copy Data', 'copyData')
    .addToUi();
}

function copyData() {
 var ss=SpreadsheetApp.getActive();
 var sheet=SpreadsheetApp.getActiveSheet();
 var range=sheet.getActiveCell();
 if (sheet.getName()=="ShopWorkList" && range.getColumn()==3 && range.getValue()=="TRUE") {
   var targetSheet=ss.getSheetByName("Sheet2");
   var targetRange=targetSheet.getRange(targetSheet.getLastRow()   1, 1);//column one
   sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);
   sheet.deleteRow(range.getRow());
 }
}

https://docs.google.com/spreadsheets/d/e/2PACX-1vRre5h3CQDhydswUi7NOBRld2j3PmOldBjXqZmjazBaTBkFRDWn6N_uFPEO8enA6LAiLCwhMoeQ8Tdr/pubhtml

CodePudding user response:

Try it this way:

function copyData() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("ShopWorkList");
  const osh = ss.getSheetByName("Sheet2");
  const vs = sh.getRange(17, 1, sh.getLastRow() - 16, sh.getLastColumn()).getValues();
  let oA = [];
  let d = 0;
  vs.forEach((r, i) => {
    if (r[2] == true) {
      oA.push(r);
      sh.deleteRow(i   17 - d  );
    }
  });
  if (oA.length > 0) {
    osh.getRange(osh.getLastRow()   1, 1, oA.length, oA[0].length).setValues(oA);
  }
}
  • Related