google-apps-scriptgoogle-sheets

Getting a macro to run using checkbox in google sheets


I'm fairly new to google sheets so I apologise in advance if this seems too basic. My macro seemed to work fine on computers, I assigned it to a 'shape' button but since it needs to also be functional on a ipad, I searched about it and the answer found was to use an onEdit(e) trigger and use checkbox to set it up. My issue now is that there's no assign button to have the macro attributed to the checkbox when it's checked :')

I have no issue sharing the script if needed because it's a very simple one.


Solution

  • Given that the code works, CarlosM's provided answer is already almost correct.

    I'll just have to combine it together with your macro

    Code:

    function onEdit(e) {
      // Update if your checkBox is located somewhere else
      var checkBoxLocation = "A1";
      // Change to false if you want to run the macro when checkBox is unticked
      var checkBoxCondition = true;
      // Since getA1Notation and getValue are both methods
      // We need to add () for them to work
      if (e.range.getA1Notation() == checkBoxLocation) {
        if (e.range.getValue() == checkBoxCondition) {
          var spreadsheet = SpreadsheetApp.getActive();
          spreadsheet.getRange('D2').activate();
          spreadsheet.duplicateActiveSheet();
          spreadsheet.getActiveSheet().setName('Estimate ');
          spreadsheet.getActiveSheet().setFrozenRows(0);
    
          var sheet = spreadsheet.getActiveSheet();
          sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).activate();
          sheet = spreadsheet.getActiveSheet();
          sheet.getRange(1, 1, sheet.getMaxRows(), sheet.getMaxColumns()).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
    
          spreadsheet.getRange('E7').activate();
          spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Clients List'), true);
          spreadsheet.deleteActiveSheet();
          spreadsheet.deleteActiveSheet();
          spreadsheet.getRange('A39:H39').activate();
        }
      }
    }
    

    The code above does execute your macro if the conditions are met. These conditions are:

    To quickly check the behavior of the logic of your script, kindly try this one. Make sure to have a checkBox in A1 before trying the code.

    Test Code:

    function onEdit(e) {
      var checkBoxLocation = "A1";
      var checkBoxCondition = true;
      if (e.range.getA1Notation() == checkBoxLocation) {
        var spreadsheet = SpreadsheetApp.getActive();
        var cell = spreadsheet.getRange('D2');
        if (e.range.getValue() == checkBoxCondition) {
          cell.setValue("A1 checkbox is ticked");
        }
        else {
          cell.setValue("A1 checkbox is unticked");
        }
      }
    }