Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- RemcoE33
- https://docs.google.com/spreadsheets/d/1AWufAtSCDN9bxJDPCc0oSN66BWHqRY_5xdn7AVwVByk/edit?usp=sharing
- */
- //Setting the ref sheet where all the columns for the dropdowns are
- const dropDownRefSheet = 'Ref';
- //Make a list of all the sheet where you want the dropdowns to appear. A = 1, B = 2 etc..
- const validation = {
- 'Sample': {
- columns: [1, 2, 3],
- rowIsGreaterThen: 1
- }
- }
- function onEdit(e) {
- const sheet = e.source.getActiveSheet();
- const range = e.range;
- const validatedSheet = validation[sheet.getName()]
- if (validatedSheet) {
- const columns = validatedSheet.columns;
- const currentColumn = range.getColumn();
- const currentRow = range.getRow();
- const max = Math.max(...columns);
- const min = Math.min(...columns);
- if (
- //Column check
- columns.includes(currentColumn) &&
- //Row check
- currentRow > validatedSheet.rowIsGreaterThen &&
- //Make sure that we not make another drowdown after the last one.
- currentColumn < max
- ) {
- //If you clear out the first dropdown, reset the rest.
- if (!e.value && currentColumn == min) {
- sheet.getRange(currentRow, min + 1, 1, (max - min) + 1)
- .clearContent()
- .clearDataValidations()
- } else {
- setDataValidation(e, columns)
- }
- }
- }
- }
- function setDataValidation(e, columns) {
- const dropdownSheet = e.source.getSheetByName(dropDownRefSheet);
- // Getting al the values from 1:1
- const headers = dropdownSheet.getRange(1, 1, 1, dropdownSheet.getLastColumn()).getValues().flat();
- //Get the column index from the value selected in the dropdown.
- const selectedHeaderIndex = headers.indexOf(e.value);
- //Get the right range for the validation rule.
- const validationRange = dropdownSheet.getRange(2, selectedHeaderIndex + 1, dropdownSheet.getLastRow());
- //Create validation rule based on range.
- const validationRule = SpreadsheetApp.newDataValidation().requireValueInRange(validationRange).build();
- //Setting the next dropdown
- e.range.offset(0, 1).clearContent().clearDataValidations();
- e.range.offset(0, 1).setDataValidation(validationRule);
- /*
- In this example there are 3 columns. Let say i have them all 3 filled in and i change the main category.
- Then i want that i set the sub offet 1 and clear all the validations and values in all the columns after offset 1
- */
- const max = Math.max(...columns);
- const currentColumn = e.range.getColumn()
- const offsetTwo = currentColumn + 2
- if (offsetTwo <= max) {
- e.source.getActiveSheet()
- .getRange(e.range.getRow(), offsetTwo, (max - offsetTwo) + 1)
- .clearContent()
- .clearDataValidations()
- }
- }
Add Comment
Please, Sign In to add comment