电子表格:动态更改DataValidation

时间:2013-08-20 09:04:24

标签: google-apps-script

我正在尝试更改范围的DataValidation,我花了很多时间知道如何处理“VALUE_IN_LIST”条件!

1 个答案:

答案 0 :(得分:0)

以下是:

function getClientsId(e) {
    Logger.clear();
    var currentSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = currentSpreadsheet.getSheetByName("data");
    var rows = sheet.getDataRange();
    var numRows = rows.getNumRows();
    var values = rows.getValues();

    var myValues = new Array();
    var myKey ;
    // Get all values
    for (var i = 0; i <= numRows - 1; i++) {
        var row = values[i];
        myKey = row[1]
        myValues[myKey ] = myKey;
    }  
    // Update the list
    var reportSheet = currentSpreadsheet.getSheetByName("report");
    var clientRange = reportSheet.getRange("aRange");
    // My main problem was the second param of 'withCriteria' function. NOTE THAT'S AN ARRAY !!!!
    var rule = SpreadsheetApp.newDataValidation().withCriteria(SpreadsheetApp.DataValidationCriteria.VALUE_IN_LIST, [Object.keys(clientsId),true]).build();
    clientRange.setDataValidation(rule);
    /*
    // Here the code if you have many rules...
    var rules = clientRange.getDataValidations();
    for (var i = 0; i < rules.length; i++) {
        for (var j = 0; j < rules[i].length; j++) {
            var rule = rules[i][j];
            if (rule != null) {
                rules[i][j] = rule.copy().withCriteria(SpreadsheetApp.DataValidationCriteria.VALUE_IN_LIST, [Object.keys(myValues),true]).build();
            }
        }
    }  
    clientRange.setDataValidations(rules);*/
}

希望这对我们有人! 的问候,