Search code examples
google-apps-scriptcheckboxundefined

onEdit() 'row is not defined' error using checkboxes


This script tries to add or remove checkboxes from column A if columns B-D are populated or not. If every cell in those three columns of that row is populated then a checkbox is inserted in column A. If even one cell in those three columns of that row is not populated, then no checkbox is inserted.

column A = checkboxes

column B = title

column C = tstart

column D = tstop

function refreshCheckboxes(){
  let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet_name');
  var rows = sheet.getDataRange().getValues();
  var headers = rows.shift();
  var checkbox = row[0]
  var title = row[1];
  var tstart = row[2];
  var tstop = row[3];
  for (var i = 0; i < rows.length; i++) {  
    if (rows[[title][tstart][tstop]] !== "") {  
      checkbox.insertCheckboxes();
    } else {
      checkbox.clearDataValidations();
      checkbox.clearContent();
    }
  }
}

CURRENT OUTCOME:

ReferenceError: row is not defined is occurring when the row variables are being set. I'm not sure why I'm getting that error because I have similar functions that define the row variables in this way. My other worry with this script is about how columns B-D are set up. Is an array appropriate here and and is there an better way to set this up?

DESIRED OUTCOME:

To identify what is causing the row definition error and correct it. To verify if that AND() functionality works.

I already have an onEdit() that works perfectly other than it applying to only one row at a time thus I wanted to make a custom to run as needed.

Thanks!


Solution

  • Use and installable trigger and edit sheet name. I assumed one header row

    function onMyEdit(e) {
      //e.source.toast('Entry');
      const sh = e.range.getSheet();
      if(sh.getName() == "Sheet Name" && e.range.columnStart > 1 && e.range.columnStart < 5 && e.range.rowStart > 1) {
        //e.source.toast("Gate1")
        const rg = sh.getRange(e.range.rowStart,1)
        if(sh.getRange(e.range.rowStart,2,1,3).getValues().flat().every(e => e)) {
          let v = rg.getDataValidation();
          if(v && v.getCriteriaType() == SpreadsheetApp.DataValidationCriteria.CHECKBOX) {
            //do nothing
          } else {
            //e.source.toast('Checkbox')
            rg.insertCheckboxes();
          }
        } else {
          //e.source.toast("clear");
          rg.clearDataValidations();
          rg.clearContent();
        }
      }
    }
    

    Demo:

    enter image description here