Google电子表格脚本在特定范围内创建数据验证

时间:2013-05-28 11:22:02

标签: google-apps-script google-spreadsheet-api

我正在尝试使用此脚本来创建数据验证,但它总是不起作用

   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());
       }

提前致谢。

3 个答案:

答案 0 :(得分:4)

到目前为止,某些函数(如getDataValidation())不再起作用,而是使用:

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);
    }

答案 1 :(得分:3)

我最终在第2680期找到答案

工作代码

        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);
        }

答案 2 :(得分:0)

2021 年的工作示例:

function set_data_validation() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dest_range = ss.getActiveSheet().getRange('A1:A10');
  var list_range = ss.getSheetByName('List').getRange('A1:A');
  var rule = SpreadsheetApp.newDataValidation()
                           .requireValueInRange(list_range)
                           .setAllowInvalid(false)
                           .build();
  var rules = dest_range.getDataValidations().map(x=>[rule]);
  dest_range.setDataValidations(rules);
}

它将为当前工作表上的单元格“A1:A10”设置数据验证“范围内的列表”。范围是名为“List”的工作表上的“A”列。