Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-macros

Google Sheets Script - How to automate "if checkbox == true, then copy row in another sheet" in the same spreadsheet?


Good day guys,

First of all, the spreadsheet is named Daily File Distribution.

So the issue here is: If a checkbox in 'Daily!H2:H100' is TRUE, then the contents from Columns 'Daily!A2:F100' are to be copied to 'Record' last row. Then clear the contents from 'Daily!A2:F100' (as deleting rows mess up the conditional formatting). And then change the checkboxes from 'Daily!G2:H2' to be FALSE.

I got this from a macro recorded (which is only for Daily!A2:F2):

function UntitledMacro() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A2:F2').activate();
  spreadsheet.setCurrentCell(spreadsheet.getRange('F2'));
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Record'), true);
  spreadsheet.getRange('A134').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Daily'), true);
  spreadsheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
  spreadsheet.getRange('G2').activate();
  spreadsheet.getCurrentCell().setValue('FALSE');
  spreadsheet.getRange('H2').activate();
  spreadsheet.getCurrentCell().setValue('FALSE');
};

Advance thanks!


Solution

  • function runOne() {
      var ss=SpreadsheetApp.getActive();
      var sh1=ss.getSheetByName('Daily');
      var sh2=ss.getSheetByName('Record');
      var rg1=sh1.getRange(2,1,99,6);
      var rg2=sh1.getRange(2,7,99,2);
      var vA1=rg1.getValues();
      var vA2=rg2.getValues();
      for(var i=0;i<vA1.length;i++) {
        if(vA2[i][1]) {
          sh2.appendRow(vA1[i])
          sh1.getRange(i+2,1,1,vA1[i].length).clear({contentsOnly: true, skipFilteredRows: true});
          vA2[i][0]=false;
          vA2[i][1]=false;
        }
      }
      rg2.setValues(vA2);
    }