How do you do dynamic / dependent drop downs in Google Sheets?

前端 未结 5 1193
清歌不尽
清歌不尽 2020-11-27 12:06

How do you get a sub-category column to populate a drop down based on the value selected in the main category drop down in google sheets?

I googled around and couldn

5条回答
  •  一生所求
    2020-11-27 12:30

    Here you have another solution based on the one provided by @tarheel

    function onEdit() {
        var sheetWithNestedSelectsName = "Sitemap";
        var columnWithNestedSelectsRoot = 1;
        var sheetWithOptionPossibleValuesSuffix = "TabSections";
    
        var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
        var activeSheet = SpreadsheetApp.getActiveSheet();
    
        // If we're not in the sheet with nested selects, exit!
        if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
            return;
        }
    
        var activeCell = SpreadsheetApp.getActiveRange();
    
        // If we're not in the root column or a content row, exit!
        if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
            return;
        }
    
        var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );
    
        // Get all possible values
        var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );
    
        var possibleValuesValidation = SpreadsheetApp.newDataValidation();
        possibleValuesValidation.setAllowInvalid( false );
        possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );
    
        activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
    }
    

    It has some benefits over the other approach:

    • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
    • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
    • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

    So, how to use it:

    1. Create the sheet where you'll have the nested selectors
    2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
    3. Paste the code attached to this answer
    4. Modify the first 3 variables of the script setting up your values and save it
    5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

    Enjoy!

提交回复
热议问题