3

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

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

提前致谢。

4

3 回答 3

6

到目前为止,像 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);
    }
于 2017-08-29T15:38:56.290 回答
3

我终于在 issue 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);
}
于 2013-05-29T08:16:50.423 回答
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”设置数据验证“范围列表”。范围是名称为“列表”的工作表上的“A”列。

于 2021-07-18T00:29:24.427 回答