简体   繁体   中英

How can i get this Script to run onEdit

I am trying to get this to run automatically, however with the current form it only works if i manually run the code.

I have another code file in this sheet which also uses onEdit, how can I incorporate the same onEdit to this code or make it run whenever column G is selected "Complete" to then change column H to "shipped"

function addValidation() {

  // Get the spreadsheet and active sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  // Get the data as an Array you can iterate and manipulate
  var data = sheet.getDataRange().getValues();

  var rule = SpreadsheetApp.newDataValidation().requireValueInList(["Complete"]).build();

  // Loop the sheet
  for(var i=0; i<data.length; i++) {


    if(data[i][11] == "Complete") {


      sheet.getRange(i+1, 8).clear().setDataValidation(rule);

    }  {
      sheet.getRange(i+1, 8).clearDataValidations().setValue("Shipped");
    }
  }
}

A couple things:

In your if statement, you're not checking Column G - you're checking column K (11). If you want to check G, you need to change your if to:

if(data[i][6].toString() == "Complete") {
  ...
}

Your logic is backward and you're missing the else keyword to run the alternative. As is, it will mark 'Shipped' if it doesn't match 'Complete.' Swap the statements to fill the cell values correctly.

Also, string checking in a loop is a little tricky. Cell references as indices are objects , not strings. You need to convert your cell using the .toString() method before you can compare a straight string.

Your whole script should read:

  function addValidation() {

  // Get the spreadsheet and active sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  // Get the data as an Array you can iterate and manipulate
  var data = sheet.getDataRange().getValues();  

  // Loop the sheet
  for(var i=0; i<data.length; i++) {

    // To change which columns you're testing, change the second value.
    // ColG = 6, not 11.
    // Convert data[i][6] using .toString() to compare the value
    if(data[i][6].toString() == "Complete") {

      // If it's "Complete," mark Col H as 'Shipped'
      sheet.getRange(i+1, 8).setValue("Shipped");

    } else {
      // If you want something else to happen, add that here.
    }
  }
}

The last step is to enable a trigger for the script. If you name your function onEdit() , it will run by itself because editing is a simple script. Since it's called addValidation , you need to manually add the onEdit trigger in the UI. Go to Edit > Current Project Triggers and click on "Add Trigger" in the bottom right. Follow the steps in the UI and the script should run itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM