Google spreadsheet Script Create Data Validation in certain range

萝らか妹 提交于 2019-12-23 16:43:29

问题


I'm trying this script to create data validation but it's always doesn't work

   function test_validation()
      {
      var Spread = SpreadsheetApp.getActiveSpreadsheet();
      var Sheet = Spread.getSheetByName('Sheet1'); 
      var validate1 = Sheet.getRange("A1").getDataValidation();
      Logger.log(validate1.getCriteria());
      Logger.log(validate1.getCriteriaValues());
      var option = new Array();
      option[0]="true";
      option[1]="1";
      option[2]="2";
      option[3]="3";
      var criteria="ITEM_IN_LIST";
      var helpText="Test Help Text"
      var Combobox = Sheet.getRange("A2").getDataValidation();
      //The line below display error 
      //"Cannot find method  (class)setCriteria(string,String[]). "
      Combobox.setCriteria(criteria,option);
      Combobox.setHelpText(helpText);
      var validate2 = Sheet.getRange("A2").setDataValidation(Combobox);
      Logger.log(Sheet.getRange("A2").getDataValidation().getCriteria());
      Logger.log(Sheet.getRange("A2").getDataValidation().getCriteriaValues());
       }

Thanks in advance.


回答1:


By now, some functions like getDataValidation() are not working anymore, instead use:

function test()
    {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
    var option = new Array();
    option[0]="0";
    option[1]="1";
    option[2]="2";
    option[3]="3";
    var dv = SpreadsheetApp.newDataValidation();
    dv.setAllowInvalid(false);
    dv.setHelpText("Some help text here");
    dv.requireValueInList(option, true);
    sheet.getRange("A3").setDataValidation(dv);
    }



回答2:


I found the answer finally in issue 2680

the working code

        function test()
        {
        var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
        var option = new Array();
        option[0]="0";
        option[1]="1";
        option[2]="2";
        option[3]="3";
        var dv = sheet.getRange("A3").getDataValidation();
        dv.setAllowInvalidData(false);
        dv.setHelpText("Some help text here");
        dv.setCriteria(SpreadsheetApp.DataValidationCriteria.ITEM_IN_LIST,true,option );
        sheet.getRange("A3").setDataValidation(dv);
        }


来源:https://stackoverflow.com/questions/16790803/google-spreadsheet-script-create-data-validation-in-certain-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!