I'm very new to coding and just trying to learn few things starting with Google sheets. I've a sample script that run on one sheet only and it will be shared spreadsheet. Here's my script
<!-- begin snippet: js hide: false console: true babel: false -->
var sheet =`enter code here` ["Main01"];
var optionList = ["Options"];
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
var wsOptions = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(optionList);
var options = wsOptions.getRange(2,1,wsOptions.getLastRow()-1,3).getValues();
var firstLevelColumn = 1;
var secondLevelColumn = 2;
var thirdLevelColumn = 3;
//Begins - main functions
function myFunction() {
} //End of myFunction
function onEdit(e) {
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var wsName = activeCell.getSheet().getName();
if(wsName == sheet && c == firstLevelColumn && r > 1 ){
firstLevelList(val,r);
} else if (wsName == sheet && c == secondLevelColumn && r > 1 ) {
secondLevelList (val,r);
}
} //End of function - onEdit
function firstLevelList(val,r) {
if(val == ""){
ws.getRange(r,secondLevelColumn).clearContent();
ws.getRange(r,secondLevelColumn).clearDataValidations();
ws.getRange(r,thirdLevelColumn).clearContent();
ws.getRange(r,thirdLevelColumn).clearDataValidations();
} //End of inner if statement
else {
ws.getRange(r,secondLevelColumn).clearContent();
ws.getRange(r,thirdLevelColumn).clearContent();
ws.getRange(r,thirdLevelColumn).clearDataValidations();
var filteredOptions = options.filter(function(op) { return op[0] == val });
var applyList = filteredOptions.map(function(op) { return op[1] });
var cell = ws.getRange(r,secondLevelColumn);
applyCellValidation(applyList,cell);
} //End of else statement
} //End of function - firstLevelList
function secondLevelList(val,r) {
//similar to firstLevelList with next level validation
} //End of function - secondLevelList
function applyCellValidation(list,cell) {
var rule = SpreadsheetApp.newDataValidation().requireValueInList(list).setAllowInvalid(false).build();
cell.setDataValidation(rule);
} //End of function - CellValidation
Some tasks I want to achieve from the code -
- Run script automatically when spreadsheet opened - maybe use onOpen() trigger. How no idea
- Since it wil be shared spreadsheet, I want script to run for each of the active sheet whenever accesed by any user.
Sheet1
- if not renamed). This means that a script that detects the active sheetonOpen
will always detect the first sheet of the spreadsheet. Is it what you want? If you want the script to run again after the user manually changed the active sheet - that cannot happenonOpen
. Also, currently your script is set uponEdit
- would you like to maintain this functionality (the script should run bothonOpen
andonEdit
) or onlyonOpen
? – ziganotschkaonEdit
trigger) anonSelectionChange
instead ofonOpen
trigger - see my answer. – ziganotschka