Change dependent drop down column in Google Script Editor - validation

How can I change this script to apply drop downs in Column B & C instead of A & B? (The script seems to work perfectly if the drop downs are in Column A & B.)
Column A will be for dates, column B will be drop down list (from "Crops" sheet) and column C will be a dependent drop down list (from "Crops" sheet). When I change the "First Level Column" (line 3) and "Second Level Column" (line 4) to equal 2 (col B) & 3 (col C) respectively in the script editor and then input a date in column A in the worksheet, the drop down options in Column B & C disappear completely.
var MainWsName = "Harvest";
var CropsWsName = "Crops";
var firstLevelColumn = 2;
var secondLevelColumn = 3;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(MainWsName);
var wsCrops = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(CropsWsName);
var Crops = wsCrops.getRange(2, 1,wsCrops.getLastRow()-1,3).getValues();
function onEdit(activeCell){
var activeCell = ws.getActiveCell();
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var wsName = activeCell.getSheet().getName();
if (wsName == MainWsName && c === firstLevelColumn && r > 1){
applyFirstLevelValidation(val,r)
}//close If
}// end onEdit
function applyFirstLevelValidation(val,r){
if(val === ""){
ws.getRange(r, secondLevelColumn).clearContent();
ws.getRange(r, secondLevelColumn).clearDataValidations();
} else {
ws.getRange(r, secondLevelColumn).clearContent();
var filteredCrops = Crops.filter(function(o){ return o[0] === val });
var listToApply = filteredCrops.map(function(o){ return o[1] });
var cell = ws.getRange(r, secondLevelColumn);
applyValidationToCell(listToApply,cell);
}
}
function applyValidationToCell(list,cell){
var rule = SpreadsheetApp
.newDataValidation()
.requireValueInList(list)
.setAllowInvalid(false)
.build();
cell.setDataValidation(rule);
}

function onEdit(e) {
if (sh.getName() == 'Harvest' && e.range.columnStart > 1 && e.range.columnStart < 4 && e.range.rowStart > 1) {
applyFirstLevelValidation(e.value, e.range.rowStart)
}
}
You can't use parameters with trigger functions. I don't see how the onEdit(e)

Related

Google Sheet Apps Script Exceeding maximum time

I have a dynamic dropdown apps script running on only 1 cell and there are some other formulas running in my sheet. Until 2 days before i could run the script onEdit but i cant seem to do so now.
When checked inside apps script execution page it shows "Exceeded maximum execution time". What can i do to resolve this?
var mainWsName = "Print Sheet";
var mainDataName = "Orders";
var FirstLevelColumn = 1;
var SecondLevelColumn = 2;
var ThirdLevelColumn = 3;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName);
var wsJO = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainDataName);
var JO = wsJO.getRange(2,1,wsJO.getLastRow()-1,2).getValues();
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 === mainWsName && c === FirstLevelColumn && r > 1){
applyFirstLevelValidation(val,r);
}else if(wsName === mainWsName && c=== SecondLevelColumn && r > 1){
applysecondLevelValidation(val,r);
}
} //end onEdit
function applyFirstLevelValidation(val,r){
if(val === ""){
ws.getRange(r,SecondLevelColumn).clearContent();
ws.getRange(r,SecondLevelColumn).clearDataValidations();
} else {
ws.getRange(r,SecondLevelColumn).clearContent();
var filteredJO = JO.filter(function(o){return o[0] === val });
var listToApply = filteredJO.map(function(o){return o[1]});
var cell = ws.getRange(r,SecondLevelColumn);
applyValidationToCell(listToApply,cell);
}
}
function applyValidationToCell(list,cell){
var rule=SpreadsheetApp.newDataValidation().requireValueInList(list).setAllowInvalid(false).build();
cell.setDataValidation(rule);
}
Tried executing app script to get dynamic dropdown based on my selection.
The code you quote is suboptimal, but chances are that the bad performance you mention is caused by the spreadsheet rather than the script. To improve spreadsheet performance, see these optimization tips.
You may also want to take a look at the dependentDropDownLists_ script.

Google Apps Script run faster

Below I have some code I have running for a spreadsheet. Right now it takes a min or two to run through the script. I was wondering if anyone has any suggestions on how to re-work my code to run a little faster.
What the code does is search on a tab in the sheet called "set up" for check-marked items in a list that I would like included in my "Master Sheet". Then go to my sheet which contains all of the information that I would like copied and pasted over according to what is check marked on my set-up page. Then copy and paste those line items to the master sheet.
function allToMaster(){
var sss = SpreadsheetApp.getActive();
var ssAll = sss.getSheetByName("FF All");
var ssMaster = sss.getSheetByName("FF Master");
var ssSetup = sss.getSheetByName("FF Setup");
ssMaster.clear();
var masterCounter = 2;
ssAll.getRange("P:P").clear();
var sourceRange = ssAll.getRange(1,1,1,15);
sourceRange.copyTo(ssMaster.getRange(1,1));
//get last row of FF All
var lastRowAll = ssAll.getLastRow();
var lastRowMaster = ssMaster.getLastRow();
ssAll.getRange("P2:P" + lastRowAll).setFormula("=index('FF Setup'!B:B,match(B2,'FF Setup'!C:C,0))");
ssMaster.setRowHeightsForced(2, 500, 26);
for (i=2;i<=lastRowAll;i++){
if (ssAll.getRange(i,1).getBackground() == "#a8d08d"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else if (ssAll.getRange(i,1).getBackground() == "#e2efd9"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else {
if (ssAll.getRange("P" + i).getValue() == true) {
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
ssMaster.setRowHeightsForced(masterCounter, 1, 136);
masterCounter++;
}
}
}
ssAll.getRange("P:P").clear();
//Clear Empty Subtitles
var lastRowMaster = ssMaster.getLastRow();
for (i=2;i<=lastRowMaster;i++){
if (ssMaster.getRange(i,1).getBackground() == "#e2efd9"){
if(ssMaster.getRange((i+1),1).getBackground() == "#e2efd9" || ssMaster.getRange((i+1),1).getBackground() == "#a8d08d"){
ssMaster.deleteRow(i);
ssMaster.insertRowAfter(500);
i=i-1;
}
}
}
//Clear Empty Titles
var lastRowMaster = ssMaster.getLastRow();
for (i=2;i<=lastRowMaster;i++){
if (ssMaster.getRange(i,1).getBackground() == "#a8d08d"){
if(ssMaster.getRange((i+1),1).getBackground() == "#a8d08d"){
ssMaster.deleteRow(i);
ssMaster.insertRowAfter(500);
i=i-1;
}
}
}
//Find the row with "Delivery"
var deliveryRow = getRowOf("DELIVERY", "FF All", 1);
var sourceRange = ssAll.getRange(deliveryRow,1,(lastRowAll - deliveryRow + 1),15);
var masterCounter = ssMaster.getLastRow()
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter = masterCounter + lastRowAll - deliveryRow - 2;
//.setFormula('=SUMA(J264:J275)');
// ssMaster.getRange(masterCounter, 10).setFormula("=sum(J2:J" + (masterCounter - 1) + ")");
//ssMaster.getRange(masterCounter, 11).setFormula("=sum(K2:K" + (masterCounter - 1) + ")");
//ssMaster.getRange(masterCounter, 13).setFormula("=sum(M2:M" + (masterCounter - 1) + ")");
//ssMaster.getRange(masterCounter, 15).setFormula("=M" + masterCounter + " - K" + masterCounter);
}
function getRowOf(value, sheet, col){
var dataArr = SpreadsheetApp.getActive().getSheetByName(sheet).getRange(4, col, 3500, 1).getValues();
for(var j = 0; j < dataArr.length; j ++){
var currVal = dataArr[j][0];
if(currVal == value){
return j+4;
break;
}
}
return 0;
}
You need to change the loops as they are doing several calls to Class SpreadsheetApp on each iteration.
Regarding the first loop,
for (i=2;i<=lastRowAll;i++){
if (ssAll.getRange(i,1).getBackground() == "#a8d08d"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else if (ssAll.getRange(i,1).getBackground() == "#e2efd9"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else {
if (ssAll.getRange("P" + i).getValue() == true) {
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
ssMaster.setRowHeightsForced(masterCounter, 1, 136);
masterCounter++;
}
}
}
Instead of getting the background of one cell at a time (ssAll.getRange(i,1).getBackground()), before the loop get the backgrounds of all the cells before the loop, i.e.
const backgrounds = ssAll.getRange(2,1,lastRowAll).getBackgrounds();
then replace ssAll.getRange(i,1).getBackground() by backgrounds[i-1][0].
Do the something similar about ssAll.getRange("P" + i).getValue(), before the loop get the all values of the P column:
const values = ssAll.getRange("P" + i + ":P" + lastRowAll).getValues()
then replace ssAll.getRange("P" + i).getValue() by values[i-1][0]`.
It might be also possible to optimize further the first loop depending on if you really need to copy the ranges (besides values, include borders, background, notes, etc.) or if you only need the values.
Another option is to use the Advances Sheets Services but this implies to make a completely different implementation.

Is there a way I can make my script more efficient?

I have created the below script to add a timestamp when a cell equals a specific value. This script repeats for each row but it is not efficient. How can I make this simpler and quicker? Below is an extract of the script, it repeats for each row
function MyFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('Overview')
var cell = sheet.getRange('H3').getValue()
var sent = sheet.getRange('p3').getValue()
if (cell == "Full" && sent == "") {
sheet.getRange('p3').setValue(new Date())
}
else if (cell == "Open" && sent == "") {
sheet.getRange('p3').setValue("")
}
}
Try this.
function MyFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Overview');
// get range H3:P were H=8, P=16, 9 columns total or index 0 to 8
var data = sheet.getRange(3,8,sheet.getLastRow()-2,9).getValues(); // get range H3:P
var i = 0;
var row = null;
for( i=0; i<data.length; i++ ) {
row = data[i];
if( ( row[0] === "Full" ) && ( row[8] === "" ) ) {
row[8] = new Date();
}
// Your else doesn't do anything if blank set blank ??
row.splice(0,8); // extract only column P
}
sheet.getRange(3,16,data.length,1).setValues(data);
}
Try using setvalues() method of class range
function MyFunction() {
const ss = SpreadsheetApp.getActive()
const sh = ss.getSheetByName('Overview');
const rg = sh.getDataRange();
const vs = rg.getValues();
let vo = vs.map(r => {
if( r[7] == "Full") r[15]=new Date()
if( r[7] == "Open") r[15]='';
return [r[15]];
});
sh.getRange(2,16,vo.length,1).setValues(vo);
}

Dyanamic Dropdown List Validation (third level) using app script

I have a script written to apply three levels of validation. The first level of validation is in column A on the "master" sheet and the second and third are in the app script.
I am able to select the first level of validation in the "master"sheet and the list is filtered to only show the relevant answers in a dropdown list in Column B. After selecting my answer in Column B, the dropdown arrow appears in Column C but there are no fields to select. I can manually enter a value that is on my list and it is accepted and any thing that is not in the list is rejected. I have narrowed my issue to:
var filteredOptions = options.filter(function(o){ return o[0] === firstLevelColValue && o[1] === val });
When I place Logger.log(filteredOptions); in function applySecondLevelValadation(val, r){, it returns with an empty array [].
When I place
Logger.log(filteredOptions);` in `function applyFirstLevelValadation(val, r){
, it returns with the array:
[[Intermediate, 9:00 AM, Upper Dumont], [Intermediate, 12:00 PM, Outer Limts], [Intermediate, 3:30 PM, Satelite], [Intermediate, 9:00 AM, Box], [Intermediate, 12:00 PM, Hidden Valley], [Intermediate, 3:30 PM, Kermits]]
Screenshot of "options" sheet
Screenshot of "master" with all possible options for column A & B and no options for selection in column C
Any help figuring out why var filteredOptions = options.filter(function(o){ return o[0] === firstLevelColValue && o[1] === val }); is returning an empty array would be great!
Code being used:
var mainWsName = "master";
var optionsWsName = "options";
var firstLevelColumn = 1;
var secondLevelColumn = 2;
var thirdLevelColumn = 3;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName);
var wsOptions = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(optionsWsName);
var options = wsOptions.getRange(2,1,wsOptions.getLastRow()-1,3).getValues();
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 === mainWsName && c === firstLevelColumn && r > 1) {
applyFirstLevelValadation(val, r);
} else if(wsName === mainWsName && c === secondLevelColumn && r > 1) {
applySecondLevelValadation(val, r);
}
}
function applyFirstLevelValadation(val, r) {
if(val === "") {
ws.getRange(r, secondLevelColumn).clearContent();
ws.getRange(r, secondLevelColumn).clearDataValidations();
ws.getRange(r, thirdLevelColumn).clearContent();
ws.getRange(r, thirdLevelColumn).clearDataValidations();
} else {
ws.getRange(r, secondLevelColumn).clearContent();
ws.getRange(r, secondLevelColumn).clearDataValidations();
ws.getRange(r, thirdLevelColumn).clearContent();
ws.getRange(r, thirdLevelColumn).clearDataValidations();
var filteredOptions = options.filter(function(o){ return o[0] === val });
var listToApply = filteredOptions.map(function(o){ return o[1] });
var cell = ws.getRange(r, secondLevelColumn);
Logger.log(filteredOptions)
applyValidationToCell(listToApply,cell);
}
}
function applySecondLevelValadation(val, r) {
if(val === "") {
ws.getRange(r, thirdLevelColumn).clearContent();
ws.getRange(r, thirdLevelColumn).clearDataValidations();
} else {
ws.getRange(r, thirdLevelColumn).clearContent();
var firstLevelColValue = ws.getRange(r, firstLevelColumn).getValue();
var filteredOptions = options.filter(function(o){ return o[0] === firstLevelColValue && o[1] === val });
var listToApply = filteredOptions.map(function(o){ return o[2] });
var cell = ws.getRange(r, thirdLevelColumn);
Logger.log(filteredOptions);
applyValidationToCell(listToApply,cell);
}
}
function applyValidationToCell(list, cell) {
var rule = SpreadsheetApp
.newDataValidation()
.requireValueInList(list)
.setAllowInvalid(false)
.build();
cell.setDataValidation(rule);
}
It looks like you are having an issue with the time column. Probably because it's comparing a string to a date or what have you. We would have more information if you shared a copy of the spreadsheet.
In any case, to avoid this, you can format data in both columns B (in 'master' as well as in 'options') as plain text (for that, go to Format > Number > Plain text in your spreadsheet). Then, you can write the trip times in 'options' as plain text.
I hope this is of any help to you.

Set the sourceRange of Data Validation to an array of values

I'm creating a social media outreach tracker. I want to create a drop-down list of the contact name. The problem is that I have two sources of names on two different sheets.
I wrote a script that pulls the names from the two different sources and combines them to a single array.
I was hoping to set the source range as that array.
Here is my code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var auditionsSheet = SpreadsheetApp.getActiveSpreadsheet();
var castingDirectorsTab = auditionsSheet.getSheetByName("Casting Directors");
var contactsTab = auditionsSheet.getSheetByName("Contacts");
var socialMediaOutreachTab = auditionsSheet.getSheetByName("Social Media Outreach");
var lastRowCD = castingDirectorsTab.getLastRow();
var lastRowContacts = contactsTab.getLastRow();
var activeCell = socialMediaOutreachTab.getActiveCell();
var activeColumn = activeCell.getColumn();
// get data
var castingDirectorNameData = castingDirectorsTab.getRange(2, 1, lastRowCD, 1).getValues();
var contactNameData = contactsTab.getRange(2, 1, lastRowContacts, 1).getValues();
//get name data to a single arrays
var castingDirectorName = [];
castingDirectorNameData.forEach(function(yr) {
castingDirectorName.push(yr[0]);
});
var contactName = [];
contactNameData.forEach(function(yr) {
contactName.push(yr[0]);
});
// get rid of the empty bits in the arrays
for (var x = castingDirectorName.length-1; x > 0; x--) {
if ( castingDirectorName[x][0] === undefined ) {
castingDirectorName.splice( x, 1 )
}
}
for (var x = contactName.length-1; x > 0; x--) {
if ( contactName[x][0] === undefined ) {
contactName.splice( x, 1 )
}
}
//combine two data sources for data validation
var combinedNames = [];
combinedNames.push(castingDirectorName + contactName);
Logger.log (combinedNames);
Logger.log( typeof combinedNames);
// data validation set up and build
if (activeColumn == 1 && auditionsSheet.getName() == "Social Media Outreach") {
var range = auditionsSheet.getRange(activeCell.getRow(), activeColumn +1);
var sourceRange = combinedNames;
setDataValid_(range, sourceRange)
}
}
When I enter a date in Col A on Social Media Outreach, nothing happens in Col 2.
I was using an existing working nested data validation script I have but the sourceRange pulls from a sheet based on the value in the active cell. Here is that code:
function setDataValid_(range, sourceRange) {
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(sourceRange, true)
.build();
range.setDataValidation(rule);
}
function onEdit() {
var aSheet = SpreadsheetApp.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
// data validation for Auditions Tab Projet Type to Project Details
if (aColumn == 9 && aSheet.getName() == 'Auditions') {
var range = aSheet.getRange(aCell.getRow(), aColumn + 1);
var sourceRange = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('RefTables!' + aCell.getValue())
setDataValid_(range, sourceRange)
}
}
For this script when I select from the data validation drop-down, a new data validation comes up in the next col with the appropriate secondary data validation.
So the question is, can the source range be set to an array or do I need to put the names back into my sheet to reference a la the second script.
I've looked through the documentation and searched and can't find an answer. I'm relatively new to GAS and am not sure of all the inner workings of the data validation builder.

Resources