If Checkbox is checked, use a script to clear spec

2019-08-24 03:24发布

问题:

I'm trying to get a checkbox to run a script on the row it is in. It needs to loop through all rows in the specified sheet.

If a checkbox is checked in Column F, I want to schedule a script to clear columns B-F.

B is a checkbox that should be set to FALSE C is a data validated input D is data validated input E is a formula that relies on data in C and D. The formula should remain.

F being true is the triggering checkbox

If F is checked, then clear contents in B,C,D, F (E shouldnt be cleared since it's a formula)

I've tried modifying scripts from here and other links without success:

Reset checkboxes to false

Using a script to generate docs from rows in Google Sheet if checkbox is checked

Google Sheets Script to Hide Row if Checkbox Checked


 function try_It(){
 deleteRow(5); //// choose col = 2 for column C, 5 for F
 }

 function deleteRowContents (col){ // col is the index of the column to check for checkbox being true

 var sh = SpreadsheetApp.getActiveSheet();
 var data = sh.getDataRange().getValues();
 var targetData = new Array();
 for(n=0;n<data.length;++n){
 if(data[n][col]!="TRUE" && data[n][col]!="FALSE"){ targetData.push(data[n])};
 }
 Logger.log(targetData);
 sh.getDataRange().clear();
 sh.getRange(1,1,targetData.length,targetData[0].length).setValues(targetData);
 }

Expected results: If Column F is checked, clear B:F in same rows.(I know this script above is not even close to being complete).

Actual results: This deletes all the formatting on the entire sheet. It doesn't clear range properly even in the column F checkbox.

回答1:

  • You want to clear the values of the column "B" to "D" and the column "F" when the checkbox of the column "F" is true.
    • In this case, you want to change the checkbox to false.
  • You don't want to clear the cell format.

If my understanding is correct, how about this modification? Please think of this as just one of several solutions. The flow of the modified script is as follows.

  • Create the range list for deleting the columns from the retrieved values.
  • Clear the content of the range list.

Modified script:

function deleteRowContents (col){ // col is the index of the column to check for checkbox being true
  var col = 6; // If the column "F" is 6, please set 6.
  var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet4"); // Modified
  var data = sh.getDataRange().getValues();

  // Below script was modified.
  var deleteRanges = data.reduce(function(ar, e, i) {
    if (e[col - 1] === true) { // Modified
      return ar.concat(["B" + (i + 1) + ":D" + (i + 1), "F" + (i + 1)]);
    }
    return ar;
  }, []);
  if (deleteRanges.length > 0) { // or if (deleteRanges.length) { // Added
    sh.getRangeList(deleteRanges).clearContent();
  }
}

References:

  • Class RangeList
  • clearContent()

If I misunderstood your question and this was not the result you want, I apologize.