Last active
January 6, 2021 21:36
-
-
Save rheajt/983d2f7af16261bef14b575ad402441b to your computer and use it in GitHub Desktop.
create data validation cells with either named ranges or columns from a sheet in Google Sheets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onOpen() { | |
SpreadsheetApp.getUi() | |
.createMenu('MULTI DATA VALIDATION') | |
.addItem('Open', 'openSidebar') | |
.addToUi(); | |
} | |
function onInstall() { | |
installEditTrigger(); | |
onOpen(); | |
} | |
function openSidebar() { | |
var html = HtmlService.createHtmlOutputFromFile('Sidebar').setTitle('Multi Data Validation'); | |
return SpreadsheetApp.getUi().showSidebar(html); | |
} | |
/** | |
* Used to fill the select field in the sidebar | |
*/ | |
function getSheets() { | |
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets(); | |
var sheetNames = []; | |
for(var i = 0; i < sheets.length; i++) { | |
sheetNames.push(sheets[i].getName()); | |
} | |
return sheetNames; | |
} | |
function getDataVals() { | |
var dataVals = PropertiesService.getDocumentProperties().getProperty('DATA_VALS'); | |
return JSON.parse(dataVals) || {}; | |
} | |
function setDataVals(dataVals) { | |
dataVals = JSON.stringify(dataVals); | |
PropertiesService.getDocumentProperties().setProperty('DATA_VALS', dataVals); | |
} | |
function installEditTrigger() { | |
var sheet = SpreadsheetApp.openById('17c1fQcEiJXRmWhdLJu7MjMfuqw3nVSsus1_jF7SBWPo'); | |
// var sheet = SpreadsheetApp.getActive(); | |
ScriptApp.newTrigger('onEdit').forSpreadsheet(sheet).onEdit().create(); | |
} | |
function onEdit(e) { | |
if(e.range.getDataValidation()) { | |
var dataVals = getDataVals(); | |
var column = e.range.getColumn() + 1; | |
var row = e.range.getRow(); | |
var adjCell = columnToLetter(column, row); | |
var subCats = dataVals[e.value.toString()]; | |
var rule = SpreadsheetApp.newDataValidation() | |
.requireValueInList(subCats, true) | |
.build(); | |
SpreadsheetApp.getActiveSheet().getRange(adjCell).setDataValidation(rule); | |
} | |
} | |
//turn numbers into "A1" format for cell value | |
function columnToLetter(column, row) { | |
var temp, letter = ''; | |
while (column > 0) { | |
temp = (column - 1) % 26; | |
letter = String.fromCharCode(temp + 65) + letter; | |
column = (column - temp - 1) / 26; | |
} | |
return letter + row; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getMultiCategories |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment