How can I create a multiple dependent dropdown in Google Sheets? [duplicate] - google-sheets

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't find any good solutions, therefore I wanted to share my own. Please see my answer below.

You can start with a google sheet set up with a main page and drop down source page like shown below.
You can set up the first column drop down through the normal Data > Validations menu prompts.
Main Page
Drop Down Source Page
After that, you need to set up a script with the name onEdit. (If you don't use that name, the getActiveRange() will do nothing but return cell A1)
And use the code provided here:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var myRange = SpreadsheetApp.getActiveRange();
var dvSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Categories");
var option = new Array();
var startCol = 0;
if(sheet.getName() == "Front Page" && myRange.getColumn() == 1 && myRange.getRow() > 1){
if(myRange.getValue() == "Category 1"){
startCol = 1;
} else if(myRange.getValue() == "Category 2"){
startCol = 2;
} else if(myRange.getValue() == "Category 3"){
startCol = 3;
} else if(myRange.getValue() == "Category 4"){
startCol = 4;
} else {
startCol = 10
}
if(startCol > 0 && startCol < 10){
option = dvSheet.getSheetValues(3,startCol,10,1);
var dv = SpreadsheetApp.newDataValidation();
dv.setAllowInvalid(false);
//dv.setHelpText("Some help text here");
dv.requireValueInList(option, true);
sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setDataValidation(dv.build());
}
if(startCol == 10){
sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).clearDataValidations();
}
}
}
After that, set up a trigger in the script editor screen by going to Edit > Current Project Triggers. This will bring up a window to have you select various drop downs to eventually end up at this:
You should be good to go after that!

Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.
Multi-line, multi-Level, multi-List, multi-Edit-Line Dependent Drop-Down Lists in Google Sheets. Script
More Info
Article
Video
Last version of the script on GitHub
This solution is not perfect, but it gives some benefits:
Let you make multiple dropdown lists
Gives more control
Source Data is placed on the only sheet, so it's simple to edit
First of all, here's working example, so you can test it before going further.
Installation:
Prepare Data
Make the first list as usual: Data > Validation
Add Script, set some variables
Done!
Prepare Data
Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:
Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.
First simple Data Validation (DV)
Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A)
On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.
Script
Paste this code into script editor:
function onEdit(event)
{
// Change Settings:
//--------------------------------------------------------------------------------------
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data1'; // name of sheet with data
var NumOfLevels = 4; // number of levels of data validation
var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,2]; // offsets for levels
// ^ means offset column #4 on one position right.
// =====================================================================================
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);
// Change Settings:
//--------------------------------------------------------------------------------------
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
// =====================================================================================
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);
}
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets)
{
//--------------------------------------------------------------------------------------
// The event handler, adds data validation for the input parameters
//--------------------------------------------------------------------------------------
var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US
//--------------------------------------------------------------------------------------
// =================================== key variables =================================
//
// ss sheet we change (TargetSheet)
// br range to change
// scol number of column to edit
// srow number of row to edit
// CurrentLevel level of drop-down, which we change
// HeadLevel main level
// r current cell, which was changed by user
// X number of levels could be checked on the right
//
// ls Data sheet (LogSheet)
//
// ======================================================================================
// Checks
var ts = event.source.getActiveSheet();
var sname = ts.getName();
if (sname !== TargetSheet) { return -1; } // not main sheet
// Test if range fits
var br = event.range;
var scol = br.getColumn(); // the column number in which the change is made
var srow = br.getRow() // line number in which the change is made
var ColNum = br.getWidth();
if ((scol + ColNum - 1) < lcol) { return -2; } // columns...
if (srow < lrow) { return -3; } // rows
// Test range is in levels
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);
if(CurrentLevel === 1) { return -4; } // out of data validations
if(CurrentLevel > NumOfLevels) { return -5; } // last level
/*
ts - sheet with validation, sname = name of sheet
NumOfLevels = 4
offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column
columnsLevels = [4,5,6,8] - Columns of validation
Columns 7 is skipped
|
1 2 3 4 5 6 7 8 9
|----+----+----+----+----+----+----+----+----+
1 | | | | | | | x | | |
|----+----+----+----+----+----+----+----+----+
2 | | | | v | V | ? | x | ? | | lrow = 2 - number of row where validation starts
|----+----+----+----+----+----+----+----+----+
3 | | | | | | | x | | |
|----+----+----+----+----+----+----+----+----+
4 | | | | | | | x | | |
|----+----+----+----+----+----+----+----+----+
| | | | |
| | | | Currentlevel = 3 - the number of level to change
| | | |
| | | br - cell, user changes: scol - column, srow - row,
| | ColNum = 1 - width
|__|________ _.....____|
| v
| Drop-down lists
|
| lcol = 4 - number of column where validation starts
*/
// Constants
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet
var RowNum = br.getHeight();
/* Adjust the range 'br'
??? !
xxx x
xxx x
xxx => x
xxx x
xxx x
*/
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum);
// Levels
var HeadLevel = CurrentLevel - 1; // main level
var X = NumOfLevels - CurrentLevel + 1; // number of levels left
// determine columns on the sheet "Data"
var KudaCol = NumOfLevels + 2;
var KudaNado = ls.getRange(1, KudaCol); // 1 place for a formula
var lastRow = ls.getLastRow();
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula
// ============================================================================= > loop >
var CurrLevelBase = CurrentLevel; // remember the first current level
for (var j = 1; j <= RowNum; j++) // [01] loop rows start
{
// refresh first val
var currentRow = br.getCell(j, 1).getRow();
loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);
} // [01] loop rows end
}
function getColumnsOffset_(offsets, lefColumn)
{
// Columns for all levels
var columnsLevels = [];
var totalOffset = 0;
for (var i = 0, l = offsets.length; i < l; i++)
{
totalOffset += offsets[i];
columnsLevels.push(totalOffset + lefColumn - 1);
}
return columnsLevels;
}
function test_getCurrentLevel()
{
var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');
var scol = 1;
/*
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
range |xxxxx|
dv range |xxxxxxxxxxxxxxxxx|
levels 1 2 3
level 2
*/
Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2
/*
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
range |xxxxxxxxxxx|
dv range |xxxxx| |xxxxx| |xxxxx|
levels 1 2 3
level 2
*/
Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2
/*
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
range |xxxxxxxxxxxxxxxxx|
dv range |xxxxx| |xxxxxxxxxxx|
levels 1 2 3
level 2
*/
Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2
/*
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
range |xxxxxxxxxxxxxxxxx|
dv range |xxxxxxxxxxx| |xxxxx|
levels 1 2 3
level 3
*/
Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3
/*
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
range |xxxxxxxxxxxxxxxxx|
dv range |xxxxxxxxxxxxxxxxx|
levels 1 2 3
level 4 (error)
*/
Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));
/*
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
range |xxxxxxxxxxxxxxxxx|
dv range |xxxxxxxxxxxxxxxxx|
levels
level 1 (error)
*/
Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1
}
function getCurrentLevel_(ColNum, br, scol, columnsLevels)
{
var colPlus = 2; // const
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }
var CurrentLevel = -1;
var level = 0;
var column = 0;
for (var i = 0; i < ColNum; i++ )
{
column = br.offset(0, i).getColumn();
level = columnsLevels.indexOf(column) + colPlus;
if (level > CurrentLevel) { CurrentLevel = level; }
}
return CurrentLevel;
}
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)
{
for (var k = 1; k <= X; k++)
{
HeadLevel = HeadLevel + k - 1;
CurrentLevel = CurrLevelBase + k - 1;
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);
var SearchText = r.getValue(); // searched text
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);
}
}
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)
{
// if nothing is chosen!
if (SearchText === '') // condition value =''
{
// kill extra data validation if there were
// columns on the right
if (CurrentLevel <= NumOfLevels)
{
for (var f = 0; f < X; f++)
{
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]);
// clean & get rid of validation
cell.clear({contentsOnly: true});
cell.clear({validationsOnly: true});
// exit columns loop
}
}
return 0; // end loop this row
}
// formula for values
var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts);
KudaNado.setFormula(formula);
// get response
var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);
var Variants = Response.length;
// build data validation rule
if (Variants === 0.0) // empty is found
{
return;
}
if(Variants >= 1.0) // if some variants were found
{
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);
var rule = SpreadsheetApp
.newDataValidation()
.requireValueInList(Response, true)
.setAllowInvalid(false)
.build();
// set validation rule
cell.setDataValidation(rule);
}
if (Variants === 1.0) // // set the only value
{
cell.setValue(Response[0]);
SearchText = null;
Response = null;
return X; // continue doing DV
} // the only value
return 0; // end DV in this row
}
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)
{
var checkVals = [];
var Offs = CurrentLevel - 2;
var values = [];
// get values and display values for a formula
for (var s = 0; s <= Offs; s++)
{
var checkR = ts.getRange(currentRow, columnsLevels[s]);
values.push(checkR.getValue());
}
var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."
var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84
var mathOpPlusVal = '';
var value = '';
// loop levels for multiple conditions
for (var i = 0; i < CurrentLevel - 1; i++) {
formula += FormulaSplitter; // =unique(filter(A2:A84;
LookCol = colName(i);
value = values[i];
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"
if ( Array.isArray(mathOpPlusVal) )
{
formula += mathOpPlusVal[0];
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84
formula += mathOpPlusVal[1];
}
else
{
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84
formula += mathOpPlusVal;
}
}
formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))
return formula;
}
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)
{
var result = '';
var splinter = '';
var type = typeof value;
// strings
if (type === 'string') return '="' + value + '"';
// date
if(value instanceof Date)
{
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+'
+ 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)'];
}
// numbers
if (type === 'number')
{
if (ReplaceCommas)
{
return '+0=' + value.toString().replace('.', ',');
}
else
{
return '+0=' + value;
}
}
// booleans
if (type === 'boolean')
{
return '=' + value;
}
// other
return '=' + value;
}
function getResponse_(allRange, l, ReplaceCommas)
{
var data = allRange.getValues();
var data_ = allRange.getDisplayValues();
var response = [];
var val = '';
for (var i = 0; i < l; i++)
{
val = data[i][0];
if (val !== '')
{
var type = typeof val;
if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);
if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')
response.push(val);
}
}
return response;
}
function colName(n) {
var ordA = 'a'.charCodeAt(0);
var ordZ = 'z'.charCodeAt(0);
var len = ordZ - ordA + 1;
var s = "";
while(n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
function getDecimalMarkIsCommaLocals() {
// list of Locals Decimal mark = comma
var LANGUAGE_BY_LOCALE = {
af_NA: "Afrikaans (Namibia)",
af_ZA: "Afrikaans (South Africa)",
af: "Afrikaans",
sq_AL: "Albanian (Albania)",
sq: "Albanian",
ar_DZ: "Arabic (Algeria)",
ar_BH: "Arabic (Bahrain)",
ar_EG: "Arabic (Egypt)",
ar_IQ: "Arabic (Iraq)",
ar_JO: "Arabic (Jordan)",
ar_KW: "Arabic (Kuwait)",
ar_LB: "Arabic (Lebanon)",
ar_LY: "Arabic (Libya)",
ar_MA: "Arabic (Morocco)",
ar_OM: "Arabic (Oman)",
ar_QA: "Arabic (Qatar)",
ar_SA: "Arabic (Saudi Arabia)",
ar_SD: "Arabic (Sudan)",
ar_SY: "Arabic (Syria)",
ar_TN: "Arabic (Tunisia)",
ar_AE: "Arabic (United Arab Emirates)",
ar_YE: "Arabic (Yemen)",
ar: "Arabic",
hy_AM: "Armenian (Armenia)",
hy: "Armenian",
eu_ES: "Basque (Spain)",
eu: "Basque",
be_BY: "Belarusian (Belarus)",
be: "Belarusian",
bg_BG: "Bulgarian (Bulgaria)",
bg: "Bulgarian",
ca_ES: "Catalan (Spain)",
ca: "Catalan",
tzm_Latn: "Central Morocco Tamazight (Latin)",
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",
tzm: "Central Morocco Tamazight",
da_DK: "Danish (Denmark)",
da: "Danish",
nl_BE: "Dutch (Belgium)",
nl_NL: "Dutch (Netherlands)",
nl: "Dutch",
et_EE: "Estonian (Estonia)",
et: "Estonian",
fi_FI: "Finnish (Finland)",
fi: "Finnish",
fr_BE: "French (Belgium)",
fr_BJ: "French (Benin)",
fr_BF: "French (Burkina Faso)",
fr_BI: "French (Burundi)",
fr_CM: "French (Cameroon)",
fr_CA: "French (Canada)",
fr_CF: "French (Central African Republic)",
fr_TD: "French (Chad)",
fr_KM: "French (Comoros)",
fr_CG: "French (Congo - Brazzaville)",
fr_CD: "French (Congo - Kinshasa)",
fr_CI: "French (Côte d’Ivoire)",
fr_DJ: "French (Djibouti)",
fr_GQ: "French (Equatorial Guinea)",
fr_FR: "French (France)",
fr_GA: "French (Gabon)",
fr_GP: "French (Guadeloupe)",
fr_GN: "French (Guinea)",
fr_LU: "French (Luxembourg)",
fr_MG: "French (Madagascar)",
fr_ML: "French (Mali)",
fr_MQ: "French (Martinique)",
fr_MC: "French (Monaco)",
fr_NE: "French (Niger)",
fr_RW: "French (Rwanda)",
fr_RE: "French (Réunion)",
fr_BL: "French (Saint Barthélemy)",
fr_MF: "French (Saint Martin)",
fr_SN: "French (Senegal)",
fr_CH: "French (Switzerland)",
fr_TG: "French (Togo)",
fr: "French",
gl_ES: "Galician (Spain)",
gl: "Galician",
ka_GE: "Georgian (Georgia)",
ka: "Georgian",
de_AT: "German (Austria)",
de_BE: "German (Belgium)",
de_DE: "German (Germany)",
de_LI: "German (Liechtenstein)",
de_LU: "German (Luxembourg)",
de_CH: "German (Switzerland)",
de: "German",
el_CY: "Greek (Cyprus)",
el_GR: "Greek (Greece)",
el: "Greek",
hu_HU: "Hungarian (Hungary)",
hu: "Hungarian",
is_IS: "Icelandic (Iceland)",
is: "Icelandic",
id_ID: "Indonesian (Indonesia)",
id: "Indonesian",
it_IT: "Italian (Italy)",
it_CH: "Italian (Switzerland)",
it: "Italian",
kab_DZ: "Kabyle (Algeria)",
kab: "Kabyle",
kl_GL: "Kalaallisut (Greenland)",
kl: "Kalaallisut",
lv_LV: "Latvian (Latvia)",
lv: "Latvian",
lt_LT: "Lithuanian (Lithuania)",
lt: "Lithuanian",
mk_MK: "Macedonian (Macedonia)",
mk: "Macedonian",
naq_NA: "Nama (Namibia)",
naq: "Nama",
pl_PL: "Polish (Poland)",
pl: "Polish",
pt_BR: "Portuguese (Brazil)",
pt_GW: "Portuguese (Guinea-Bissau)",
pt_MZ: "Portuguese (Mozambique)",
pt_PT: "Portuguese (Portugal)",
pt: "Portuguese",
ro_MD: "Romanian (Moldova)",
ro_RO: "Romanian (Romania)",
ro: "Romanian",
ru_MD: "Russian (Moldova)",
ru_RU: "Russian (Russia)",
ru_UA: "Russian (Ukraine)",
ru: "Russian",
seh_MZ: "Sena (Mozambique)",
seh: "Sena",
sk_SK: "Slovak (Slovakia)",
sk: "Slovak",
sl_SI: "Slovenian (Slovenia)",
sl: "Slovenian",
es_AR: "Spanish (Argentina)",
es_BO: "Spanish (Bolivia)",
es_CL: "Spanish (Chile)",
es_CO: "Spanish (Colombia)",
es_CR: "Spanish (Costa Rica)",
es_DO: "Spanish (Dominican Republic)",
es_EC: "Spanish (Ecuador)",
es_SV: "Spanish (El Salvador)",
es_GQ: "Spanish (Equatorial Guinea)",
es_GT: "Spanish (Guatemala)",
es_HN: "Spanish (Honduras)",
es_419: "Spanish (Latin America)",
es_MX: "Spanish (Mexico)",
es_NI: "Spanish (Nicaragua)",
es_PA: "Spanish (Panama)",
es_PY: "Spanish (Paraguay)",
es_PE: "Spanish (Peru)",
es_PR: "Spanish (Puerto Rico)",
es_ES: "Spanish (Spain)",
es_US: "Spanish (United States)",
es_UY: "Spanish (Uruguay)",
es_VE: "Spanish (Venezuela)",
es: "Spanish",
sv_FI: "Swedish (Finland)",
sv_SE: "Swedish (Sweden)",
sv: "Swedish",
tr_TR: "Turkish (Turkey)",
tr: "Turkish",
uk_UA: "Ukrainian (Ukraine)",
uk: "Ukrainian",
vi_VN: "Vietnamese (Vietnam)",
vi: "Vietnamese"
}
var SS = SpreadsheetApp.getActiveSpreadsheet();
var LocalS = SS.getSpreadsheetLocale();
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {
return false;
}
//Logger.log(true);
return true;
}
/*
function ReplaceDotsToCommas(dataIn) {
var dataOut = dataIn.map(function(num) {
if (isNaN(num)) {
return num;
}
num = num.toString();
return num.replace(".", ",");
});
return dataOut;
}
*/
Here's set of variables that are to be changed, you'll find them in script:
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.

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:
Create the sheet where you'll have the nested selectors
Go to the "Tools" > "Script Editor…" and select the "Blank project" option
Paste the code attached to this answer
Modify the first 3 variables of the script setting up your values and save it
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!

Edit: The answer below may be satisfactory, but it has some drawbacks:
There is a noticeable pause for the running of the script. I'm on a 160 ms latency, and it's enough to be annoying.
It works by building a new range each time you edit a given row. This gives an 'invalid contents' to previous entries some of the time
I hope others can clean this up somewhat.
Here's another way to do it, that saves you a ton of range naming:
Three sheets in the worksheet: call them Main, List, and DRange (for dynamic range.)
On the Main sheet, column 1 contains a timestamp. This time stamp is modified onEdit.
On List your categories and subcategories are arranged as a simple list. I'm using this for plant inventory at my tree farm, so my list looks like this:
Group | Genus | Bot_Name
Conifer | Abies | Abies balsamea
Conifer | Abies | Abies concolor
Conifer | Abies | Abies lasiocarpa var bifolia
Conifer | Pinus | Pinus ponderosa
Conifer | Pinus | Pinus sylvestris
Conifer | Pinus | Pinus banksiana
Conifer | Pinus | Pinus cembra
Conifer | Picea | Picea pungens
Conifer | Picea | Picea glauca
Deciduous | Acer | Acer ginnala
Deciduous | Acer | Acer negundo
Deciduous | Salix | Salix discolor
Deciduous | Salix | Salix fragilis
...
Where | indicates separation into columns.
For convenience I also used the headers as names for named ranges.
DRrange A1 has the formula
=Max(Main!A2:A1000)
This returns the most recent timestamp.
A2 to A4 have variations on:
=vlookup($A$1,Inventory!$A$1:$E$1000,2,False)
with the 2 being incremented for each cell to the right.
On running A2 to A4 will have the currently selected Group, Genus and Species.
Below each of these, is a filter command something like this:
=unique(filter(Bot_Name,REGEXMATCH(Bot_Name,C1)))
These filters will populate a block below with matching entries to the contents of the top cell.
The filters can be modified to suit your needs, and to the format of your list.
Back to Main: Data validation in Main is done using ranges from DRange.
The script I use:
function onEdit(event) {
//SETTINGS
var dynamicSheet='DRange'; //sheet where the dynamic range lives
var tsheet = 'Main'; //the sheet you are monitoring for edits
var lcol = 2; //left-most column number you are monitoring; A=1, B=2 etc
var rcol = 5; //right-most column number you are monitoring
var tcol = 1; //column number in which you wish to populate the timestamp
//
var s = event.source.getActiveSheet();
var sname = s.getName();
if (sname == tsheet) {
var r = event.source.getActiveRange();
var scol = r.getColumn(); //scol is the column number of the edited cell
if (scol >= lcol && scol <= rcol) {
s.getRange(r.getRow(), tcol).setValue(new Date());
for(var looper=scol+1; looper<=rcol; looper++) {
s.getRange(r.getRow(),looper).setValue(""); //After edit clear the entries to the right
}
}
}
}
Original Youtube presentation that gave me most of the onEdit timestamp component:
https://www.youtube.com/watch?v=RDK8rjdE85Y

Continuing the evolution of this solution I've upped the ante by adding support for multiple root selections and deeper nested selections. This is a further development of JavierCane's solution (which in turn built on tarheel's).
/**
* "on edit" event handler
*
* Based on JavierCane's answer in
*
* http://stackoverflow.com/questions/21744547/how-do-you-do-dynamic-dependent-drop-downs-in-google-sheets
*
* Each set of options has it own sheet named after the option. The
* values in this sheet are used to populate the drop-down.
*
* The top row is assumed to be a header.
*
* The sub-category column is assumed to be the next column to the right.
*
* If there are no sub-categories the next column along is cleared in
* case the previous selection did have options.
*/
function onEdit() {
var NESTED_SELECTS_SHEET_NAME = "Sitemap"
var NESTED_SELECTS_ROOT_COLUMN = 1
var SUB_CATEGORY_COLUMN = NESTED_SELECTS_ROOT_COLUMN + 1
var NUMBER_OF_ROOT_OPTION_CELLS = 3
var OPTION_POSSIBLE_VALUES_SHEET_SUFFIX = ""
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
var activeSheet = SpreadsheetApp.getActiveSheet()
if (activeSheet.getName() !== NESTED_SELECTS_SHEET_NAME) {
// Not in the sheet with nested selects, exit!
return
}
var activeCell = SpreadsheetApp.getActiveRange()
// Top row is the header
if (activeCell.getColumn() > SUB_CATEGORY_COLUMN ||
activeCell.getRow() === 1 ||
activeCell.getRow() > NUMBER_OF_ROOT_OPTION_CELLS + 1) {
// Out of selection range, exit!
return
}
var sheetWithActiveOptionPossibleValues = activeSpreadsheet
.getSheetByName(activeCell.getValue() + OPTION_POSSIBLE_VALUES_SHEET_SUFFIX)
if (sheetWithActiveOptionPossibleValues === null) {
// There are no further options for this value, so clear out any old
// values
activeSheet
.getRange(activeCell.getRow(), activeCell.getColumn() + 1)
.clearDataValidations()
.clearContent()
return
}
// 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())
} // onEdit()
As Javier says:
Create the sheet where you'll have the nested selectors
Go to the "Tools" > "Script Editor…" and select the "Blank project"
option
Paste the code attached to this answer
Modify the constants at the top of the script setting up your values
and save it
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.
And if you wanted to see it in action I've created a demo sheet and you can see the code if you take a copy.

Related

Google Sheets Query - transform rows before a query

I have a Google Sheets table similar to this:
| date | buyer | country | item 1 | item 2 | item 3 | ...
| 2022\1\1 | A.B. | LAT | milk | coffee | sugar | ...
| 2022\1\2 | C.D. | GER | milk | cocoa | cookies | ...
Is it possible to transform it somehow to a table, that has only one item per row, example:
| date | buyer | country | item |
| 2022\1\1 | A.B. | LAT | milk |
| 2022\1\1 | A.B. | LAT | coffee |
| 2022\1\1 | A.B. | LAT | sugar |
| 2022\1\2 | C.D. | GER | milk |
| 2022\1\2 | C.D. | GER | cocoa |
| 2022\1\2 | C.D. | GER | cookies |
So that I can afterward query it for what was sold when and where.
In a regular DB, I would have two (or 3) tables with 1-N relations doing a simple join/joins, but I cannot figure out how to do it in google sheets. Any ideas?
Paste this simple QUERY function formula in H2.
=QUERY({A2:C,D2:D;A2:C,E2:E;A2:C,F2:F}, " Select * Where Col1 is not null ")
And this in H1.
=ArrayFormula({A1:C1,"Items"})
Like this, take a look at the spreadsheet example.
Answer
The following formula should produce the result you desire:
=FILTER({{A2:C;A2:C;A2:C},{D2:D;E2:E;F2:F}},NOT(ISBLANK({A2:A;A2:A;A2:A})))
Explanation
This creates an array where each entry in columns A through C is duplicated three times, once for each entry in columns D through F. The =FILTER then returns only rows where column A is not empty.
Note that this is not an easily scalable function if you have a large number of different item columns to parse.
Functions used:
=FILTER
=NOT
=ISBLANK
Formula =ArrayFormula(SPLIT(FLATTEN(FILTER(A2:A&"|"&B2:B&"|"&C2:C&"|"&D2:F,A2:A<>"")),"|"))
Note: You only need to change the range when there are many items
3 items => D2:F
4 items => D2:G
5 items => D2:H
...
Function References
FILTER
FLATTEN
SPLIT
As another alternative. You can also utilize AppScript to do so. I developed a project that you can review with access to a Sheet and access "Extensions" and open the AppScript Project.
Sheet
You just need to run the function. It was based on a Macro from one of my Excel projects. Sample below.
/** #OnlyCurrentDoc */
function concatenarItems() {
// Declarando las variables necesarias
var LastColumn = 0;
var LastRow = 0;
var i = 0; // rows
var j = 0; //gathering data
var iT = 0;
var jT = 0;
var jR = 0; // extra items
var dte = ''; // Date
var buyer = ''; // buyer
var country = ''; // country
var items; // row of items
// finding the last
LastColumn =
6; // columns
var dummy_RowIndex = countCells(getActiveSheetRows());
LastRow = convertToInteger(getRowIndex(makeIterableRangeList(
getLastCellInRange(getCells(SpreadsheetApp.getActiveSheet(), dummy_RowIndex, 1), xlUp))));
// original table
i = 1;
j = 1;
// Ubicacion de la nueva tabla
iT = 2; // row
jT = 8; // Column
while (_vba_operator_lt(i, LastRow)) {
// Save row
var dummy_RowIndex_2 = _vba_operator_add(i, 1);
dte = convertToString(getRangeValue(
xlRangeValueDefault,
getCells(SpreadsheetApp.getActiveSheet(), dummy_RowIndex_2, j).rangeList));
var dummy_RowIndex_3 = _vba_operator_add(i, 1);
var dummy_ColumnIndex = _vba_operator_add(j, 1);
buyer = convertToString(getRangeValue(
xlRangeValueDefault,
getCells(SpreadsheetApp.getActiveSheet(), dummy_RowIndex_3, dummy_ColumnIndex).rangeList));
var dummy_RowIndex_4 = _vba_operator_add(i, 1);
var dummy_ColumnIndex_2 = _vba_operator_add(j, 2);
country = convertToString(getRangeValue(
xlRangeValueDefault,
getCells(SpreadsheetApp.getActiveSheet(), dummy_RowIndex_4, dummy_ColumnIndex_2)
.rangeList));
var dummy_RowIndex_5 = _vba_operator_add(i, 1);
var dummy_ColumnIndex_3 = _vba_operator_add(j, 3);
items = getRangeValue(
xlRangeValueDefault,
getCells(SpreadsheetApp.getActiveSheet(), dummy_RowIndex_5, dummy_ColumnIndex_3)
.rangeList); //save item
// save row
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, jT),
verifyRangeValueType(xlRangeValueDefault, dte));
// date
var dummy_ColumnIndex_4 = _vba_operator_add(jT, 1);
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, dummy_ColumnIndex_4),
verifyRangeValueType(xlRangeValueDefault, buyer));
// buyer
var dummy_ColumnIndex_5 = _vba_operator_add(jT, 2);
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, dummy_ColumnIndex_5),
verifyRangeValueType(xlRangeValueDefault, country));
// country
var dummy_ColumnIndex_6 = _vba_operator_add(jT, 3);
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, dummy_ColumnIndex_6),
verifyRangeValueType(xlRangeValueDefault, items));
// items
jR = 4; // count reset
// Rest of items.
while (_vba_operator_lt(jR, _vba_operator_add(LastColumn, 1))) {
var dummy_RowIndex_6 = _vba_operator_add(i, 1);
items = defaultRangeGetter(getCells(
SpreadsheetApp.getActiveSheet(), dummy_RowIndex_6,
jR)); // rewrite item
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, jT),
verifyRangeValueType(xlRangeValueDefault, dte));
var dummy_ColumnIndex_7 = _vba_operator_add(jT, 1);
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, dummy_ColumnIndex_7),
verifyRangeValueType(xlRangeValueDefault, buyer));
var dummy_ColumnIndex_8 = _vba_operator_add(jT, 2);
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, dummy_ColumnIndex_8),
verifyRangeValueType(xlRangeValueDefault, country));
var dummy_ColumnIndex_9 = _vba_operator_add(jT, 3);
setValueForRangeList(
getCells(SpreadsheetApp.getActiveSheet(), iT, dummy_ColumnIndex_9),
verifyRangeValueType(xlRangeValueDefault, items));
iT = _vba_operator_add(iT, 1);
jR = _vba_operator_add(jR, 1);
}
i = _vba_operator_add(i, 1);
}
}

Dart: how to convert a column letter into number

Currently using Dart with gsheets_api, which don't seem to have a function to convert column letters to numbers (column index)
As an example , this is what I use with AppScript (input: column letter, output: column index number):
function Column_Nu_to_Letter(column_nu)
{
var temp, letter = '';
while (column_nu > 0)
{
temp = (column_nu - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column_nu = (column_nu - temp - 1) / 26;
}
return letter;
};
This is the code I came up for Dart, it works, but I am sure there is a more elegant or correct way to do it.
String colLetter = 'L'; //Column 'L' as example
int c = "A".codeUnitAt(0);
int end = "Z".codeUnitAt(0);
int counter = 1;
while (c <= end) {
//print(String.fromCharCode(c));
if(colLetter == String.fromCharCode(c)){
print('Conversion $colLetter = $counter');
}
counter++;
c++;
}
// this output L = 12
Do you have any suggestions on how to improve this code?
First we need to agree on the meaning of the letters.
I believe the traditional approach is "A" is 1, "Z" is 26, "AA" is 27, "AZ" is 52, "BA" is 53, etc.
Then I'd probably go with something like these functions for converting:
int lettersToIndex(String letters) {
var result = 0;
for (var i = 0; i < letters.length; i++) {
result = result * 26 + (letters.codeUnitAt(i) & 0x1f);
}
return result;
}
String indexToLetters(int index) {
if (index <= 0) throw RangeError.range(index, 1, null, "index");
const _letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (index < 27) return _letters[index - 1];
var letters = <String>[];
do {
index -= 1;
letters.add(_letters[index.remainder(26)]);
index ~/= 26;
} while (index > 0);
return letters.reversed.join("");
}
The former function doesn't validate that the input only contains letters, but it works correctly for strings containing only letters (and it ignores case as a bonus).
The latter does check that the index is greater than zero.
A simplified version base on Irn's answer
int lettersToIndex(String letters) =>
letters.codeUnits.fold(0, (v, e) => v * 26 + (e & 0x1f));
String indexToLetters(int index) {
var letters = '';
do {
final r = index % 26;
letters = '${String.fromCharCode(64 + r)}$letters';
index = (index - r) ~/ 26;
} while (index > 0);
return letters;
}

Google Sheet formula for cumulative sum with condition

I have a Google Sheet with the following layout:
Number | Counted? | Cumulative Total
4 | Y | 4
2 | | 6
9 | Y | 15
... | ... | ...
The first cell in the Cumulative Total column is populated with this formula:
=ArrayFormula((SUMIF(ROW(C2:C1000),"<="&ROW(C2:1000),C2:C1000)
However this counts all rows in the 'Number' column. How can I make the Cumulative Total only count rows where the Counted? cell is Y?
Try this in C2 and copy down:
= N(C1) + A2 * (B2 = "Y")
Update
Doesn't seem to work with SUMIFS, but there is a very slow matrix multiplication alternative:
=ArrayFormula(MMult((Row(2:1000)>=Transpose(Row(2:1000)))*Transpose(A2:A1000*(B2:B1000="Y")), Row(2:1000)^0))
Assuming "Number" in column A and "Counted?" in column B, try in C1
={"SUM"; ArrayFormula(if(ISBLANK(B2:B),,mmult(transpose(if(transpose(row(B2:B))>=row(B2:B), if(B2:B="Y", A2:A,0), 0)),row(B2:B)^0)))}
(Change ranges to suit).
Example
custom formula sample:
=INDEX(IF(B3:B="","", runningTotal(B3:B,1,,A3:A)))
sample file
source code
related
code:
/**
* Get running total for the array of numbers
* by makhrov.max#gmail.com
*
* #param {array} numbers The array of numbers
* #param {number} total_types (1-dafault) sum, (2) avg, (3) min, (4) max, (5) count;
* 1-d array or number
* #param {number} limit number of last values to count next time.
* Set to 0 (defualt) to take all values
* #param {array} keys (optional) array of keys. Function will group result by keys
* #return The hex-code of cell background & font color
* #customfunction
*/
function runningTotal(numbers, total_types, limit, keys) {
// possible types to return
var oTypes = {
'1': 'sum',
'2': 'avg',
'3': 'min',
'4': 'max',
'5': 'count'
}
// checks and defaults
var errPre = '🥴 ';
if( typeof numbers != "object" ) {
numbers = [ [numbers] ];
}
total_types = total_types || [1];
if( typeof total_types != "object" ) {
total_types = [ total_types ];
}
if( keys && typeof keys != "object" ) {
keys = [ [keys] ];
}
if (keys) {
if (numbers.length !== keys.length) {
throw errPre + 'Numbers(' +
numbers.length +
') and keys(' +
keys.length +
') are of different length'; }
}
// assign types
var types = [], type, k;
for (var i = 0; i < total_types.length; i++) {
k = '' + total_types[i];
type = oTypes[k];
if (!type) {
throw errPre + 'Unknown total_type = ' + k;
}
types.push(type);
}
limit = limit || 0;
if (isNaN(limit)) {
throw errPre + '`limit` is not a Number!';
}
limit = parseInt(limit);
// calculating running totals
var result = [],
subres = [],
nodes = {},
key = '-',
val;
var defaultNode_ = {
values: [],
count: 0,
sum: 0,
max: null,
min: null,
avg: null,
maxA: Number.MIN_VALUE,
maxB: Number.MIN_VALUE,
maxC: Number.MIN_VALUE,
minA: Number.MAX_VALUE,
minB: Number.MAX_VALUE,
minC: Number.MAX_VALUE
};
for (var i = 0; i < numbers.length; i++) {
val = numbers[i][0];
// find correct node
if (keys) { key = keys[i][0]; }
node = nodes[key] ||
JSON.parse(JSON.stringify(defaultNode_));
/**
* For findig running Max/Min
* sourse of algorithm
* https://www.geeksforgeeks.org
* /sliding-window-maximum-maximum-of-all-subarrays-of-size-k/
*/
// max
//reset first second and third largest elements
//in response to new incoming elements
if (node.maxA<val) {
node.maxC = node.maxB;
node.maxB = node.maxA;
node.maxA = val;
} else if (node.maxB<val) {
node.maxC = node.maxB;
node.maxB = val;
} else if (node.maxC<val) {
node.maxC = val;
}
// min
if (node.minA>val) {
node.minC = node.minB;
node.minB = node.minA;
node.minA = val;
} else if (node.minB>val) {
node.minC = node.minB;
node.minB = val;
} else if (node.minC>val) {
node.minC = val;
}
// if limit exceeds
if (limit !== 0 && node.count === limit) {
//if the first biggest we earlier found
//is matching from the element that
//needs to be removed from the subarray
if(node.values[0]==node.maxA) {
//reset first biggest to second and second to third
node.maxA = node.maxB;
node.maxB = node.maxC;
node.maxC = Number.MIN_VALUE;
if (val <= node.maxB) {
node.maxC = val;
}
} else if (node.values[0]==node.maxB) {
node.maxB = node.maxC;
node.maxC = Number.MIN_VALUE;
if (val <= node.maxB) {
node.maxC = val;
}
} else if (node.values[0]==node.maxC) {
node.maxC = Number.MIN_VALUE;
if (val <= node.maxB) {
node.maxC = val;
}
} else if(node.values[0]==node.minA) {
//reset first smallest to second and second to third
node.minA = node.minB;
node.minB = node.minC;
node.minC = Number.MAX_VALUE;
if (val > node.minB) {
node.minC = val;
}
}
if (node.values[0]==node.minB) {
node.minB = node.minC;
node.minC = Number.MAX_VALUE;
if (val > node.minB) {
node.minC = val;
}
}
if (node.values[0]==node.minC) {
node.minC = Number.MAX_VALUE;
if (val > node.minB) {
node.minC = val;
}
}
// sum
node.sum -= node.values[0];
// delete first value
node.values.shift();
// start new counter
node.count = limit-1;
}
// add new values
node.count++;
node.values.push(val);
node.sum += val;
node.avg = node.sum/node.count;
node.max = node.maxA;
node.min = node.minA;
// remember entered values for the next loop
nodes[key] = node;
// get the result depending on
// selected total_types
subres = [];
for (var t = 0; t < types.length; t++) {
subres.push(node[types[t]]);
}
result.push(subres);
}
// console.log(JSON.stringify(nodes, null, 4));
return result;
}

SOLVE function better solution

I have a spreadsheet where a lot of cells are multiplied with a CONSTANT value and added and the result (SOLL) differs from the expected (IST) value and the only way I was able to find, was to make 10 iterations modifying each time the CONSTANT value till the SOLL and IST are pretty equal.
My method looks too stupid and I am just asking a beautiful and intelligent way to solve it...
thanks
function costante()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); //spreadsheet "options"
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]); //sheet nr.1
var sheet = SpreadsheetApp.getActiveSheet();
for(var i=0; i<10; i++){
var dataRange = sheet.getRange("o5:o5"); //marge ist
var mist = dataRange.getValues();
var dataRange = sheet.getRange("o4:o4"); //marge soll
var msoll = dataRange.getValues();
var dataRange = sheet.getRange("n1:n1"); //costante
var costante = dataRange.getValues();
var minus = 1;
if(mist - msoll < 0) { minus = -1};
costante = mist / msoll * minus * costante;
sheet.getRange("n1:n1").setValues([[costante]]);}
}
Maybe what you want, assuming your "lot of cells" are in A1:A10 and the IST value is in E1 is:
=E1/sum(A1:A10)
but please note the tag wiki.
thanks, I was first surprised by the simple method and I checked it:
10 values and their addition gives for instance = 10 (sum(a1:a10))
the IST value that I would like to have is 500 (E1)
E1/sum(A1:A10) = 500/10 = 50 = C (COSTANTE)
E1 = Sum(A1:A10) x C
if I multiply each A(y) value with 50, I have 500 and the proposed formula would perfectly work
BUT I forgot to mention that the values of A(y) are formulas that include already my COSTANTE it means that in reality each A(y) value is a formula that contains C
E1 = Sum( A(y) x C ) x C
a) for that reason the solution proposed does not give the needed value, and I was obliged to repeat the calculation ca.10 times
b) I also added a delay of 1 second because I was not sure if the spreadsheet is able to calculate so fast (please tell me if it is necessary)
c) and I said that if the result is +/- 2 from expected value, to stop to calculate
It works but is still not beautiful...
function costante()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); //spreadsheet "options"
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]); //sheet nr.1
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("o5:o5"); //marge ist
var mist = dataRange.getValues();
for(var i=0; i<20; i++)
{
var dataRange = sheet.getRange("o4:o4"); //marge soll
var msoll = dataRange.getValues();
var dataRange = sheet.getRange("n1:n1"); //costante
var costante = dataRange.getValues();
var diff = msoll - mist;
if(diff < -2) { costante = costante * 1.005;}
else if (diff > 2) { costante = costante * 0.995;}
else {return;}
sheet.getRange("n1:n1").setValues([[costante]]);
Utilities.sleep(1000); //wait 1.5sec
}
}

How to get sum of values in grid?

For example I have grid.
//grid for answers_for_online
var answersGridForOnline5 = new Ext.grid.GridPanel({
id : 'grid_for_stats',
store : storez3,
columns : answers_columns5,
});
my column:
var answers_columns5 = [{
id: "idz",
header: 'idz',
dataIndex: "idz",
renderer: fun_f
}];
and renderer function
function fun(n, j, k, m, h, i) {
var count = store.snapshot ? store.snapshot.length : store.getCount()
var cez = k.get("scale")
var ce = ( 2 / count ) * 100
return ce + " % "
}
Question: In database I have for example: scales (that user answered on scale-question)
id | scale
1 | 4
2 | 4
3 | 1
4 | 2
How i can sum scales (and group them of course) and put this in my grid?
For example in my grid i should get:
scale | scale %
1 | 25%
2 | 25%
4 | 50%
I advise you don't attempt to do it inside Grid/Store. Instead process the data before loading it to store - for example do it in database with GROUP BY statement.
To get the sum of values in a store, you can use Store.sum()

Resources