Automatic hiding columns based on cell value in google spreadsheets - google-sheets

I have too many columns in the sheet and so many columns to hide as well, but while executing the script it runs half way and stopped saying maximum time reached.
When I again tried to execute it stopped exactly where I stopped previously. So I would like to have some customization that if the column is already hidden can skip that column and work on the others.
Is there any way to do it.
Here is the code I used:
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var numCols = sh.getMaxColumns();
var numRows = sh.getMaxRows();
for(var i = 0; i <= numCols; i++){
if(data[0][i] == ""){
sh.hideColumns(i+1);
} else {
sh.unhideColumn(sh.getRange(1, i+1, numRows, 1));
}
}
}
Please help me.

You can use the documentProperties to store the last column before the end of the execution. To prevent the run from stopping abruptly you stop the run a little prematurely at 5min (execution will terminate at 6min mark) mark and store the column number in the documentProperty. You also display an alert asking you rerun the script.
Then retrieve the column number on the next run and start from there. If the program gets through the complete loop you delete the said properties. So you start from zero if you rerun the script next time.
Below is the code for the same
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var numCols = sh.getMaxColumns();
var numRows = sh.getMaxRows();
var docProp = PropertiesService.getDocumentProperties()
var startCol = Number(docProp.getProperty("startCol")) //if there is no propert called startCol will return Null, Number(Null) = 0
Logger.log(startCol)
var startTime = new Date().getTime()
var ms5min = 5*60*1000 //5min in millseconds
for(var i = startCol; i <= numCols; i++){
if(data[0][i] == ""){
sh.hideColumns(i+1);
} else {
sh.unhideColumn(sh.getRange(1, i+1, numRows, 1));
}
var curTime = new Date().getTime()
var elasped = curTime-startTime
if (elasped >= ms5min){
docProp.setProperty("startCol", i)
SpreadsheetApp.getUi().alert("Please restart Run, exceeded 5min mark")
return
}
}
Logger.log(elasped)
docProp.deleteAllProperties()
}

If your sheet has under 10,000 columns (PropertiesService limit) you can use this script:
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var documentProperties = PropertiesService.getDocumentProperties()
var documentPropertiesVals = documentProperties.getProperties();
var numCols = sh.getMaxColumns();
for(var i = 0; i < numCols; i++){
if (!(cPlusInt(i) in documentPropertiesVals)) {
documentPropertiesVals[cPlusInt(i)] === 'empty';
}
if (documentPropertiesVals[cPlusInt(i)] === 'hidden' && data[0][i] == "") continue;
if (documentPropertiesVals[cPlusInt(i)] === 'unhidden' && data[0][i] != "") continue;
if(data[0][i] == ""){
sh.hideColumns(i+1);
documentProperties.setProperty(cPlusInt(i), 'hidden')
} else {
sh.unhideColumn(sh.getRange(1, i+1, 1, 1));
documentProperties.setProperty(cPlusInt(i), 'unhidden')
}
}
}
function cPlusInt(num) {
return 'c'+num.toString()
}
You at first you may need to run this few times (many write operation to PropertiesService may be sluggish) but later it's "blazingly" fast (0.1 s per new column).
Better answer using #Jack Brown's idea
It is possible to make single save to PropertiesService - you would need to incorporate time limit from #Jack Brown's answer, this way:
function hideColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('ANALYTIC');
var data = sh.getRange('6:6').getValues();
var documentProperties = PropertiesService.getDocumentProperties()
var documentPropertiesVals = documentProperties.getProperties();
var numCols = sh.getMaxColumns();
var startTime = new Date().getTime()
var ms5min = 5*60*1000 //5min in millseconds
for(var i = 0; i < numCols; i++){
if (!(cPlusInt(i) in documentPropertiesVals)) {
documentPropertiesVals[cPlusInt(i)] === 'empty';
}
if (documentPropertiesVals[cPlusInt(i)] === 'hidden' && data[0][i] == "") continue;
if (documentPropertiesVals[cPlusInt(i)] === 'unhidden' && data[0][i] != "") continue;
if(data[0][i] == ""){
sh.hideColumns(i+1);
documentPropertiesVals[cPlusInt(i)] = 'hidden'
} else {
sh.unhideColumn(sh.getRange(1, i+1, 1, 1));
documentPropertiesVals[cPlusInt(i)] = 'unhidden'
}
var curTime = new Date().getTime()
var elapsed = curTime-startTime
if (elapsed >= ms5min){
break;
}
}
documentProperties.setProperties(documentPropertiesVals)
if (elapsed >= ms5min){
SpreadsheetApp.getUi().alert("Please restart Run, exceeded 5min mark")
}
}
cPlusInt function explanation
cPlusInt is necessary because of weird problems with google's PropertiesService. Object gotten from PropertiesService returns undefined at integer keys. To see problem use this code:
function test() {
var obj = {};
for (var i=0; i<10; i++) {
obj[i.toString()] = 'aa' + i.toString();
}
var documentProperties = PropertiesService.getScriptProperties();
documentProperties.deleteAllProperties();
documentProperties.setProperties(obj);
obj = documentProperties.getProperties();
Logger.log(obj)
for (var i in obj) {
Logger.log('%s %s %s', i, obj[i], i === '1');
}
}

Related

How can I make a function in google sheet run on all the previous cells above until the previous function

I want to make a function in google sheet, for example here "sum" I want it sum all above cells until the previous another function
So if I copied it to another row it will sum all above cell until the previous function also (3 of pic).
Try these custom functions
// mike steelson
function sumSinceLastFormula(rng){
var lastRow = SpreadsheetApp.getActiveRange().getRow()-1
var col = SpreadsheetApp.getActiveRange().getColumn()
var sum=0
for (var i = lastRow; i>1; i--){
var value = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i,col).getFormula()
if (value && value.toString().charAt(0) === '=') {break}
else {sum += SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i,col).getValue()}
}
return sum
}
function countaSinceLastFormula(rng){
var lastRow = SpreadsheetApp.getActiveRange().getRow()-1
var col = SpreadsheetApp.getActiveRange().getColumn()
var counta=0
for (var i = lastRow; i>1; i--){
var value = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i,col).getFormula()
if (value && value.toString().charAt(0) === '=') {break}
else {counta++}
}
return counta
}
function countifSinceLastFormula(rng,crit){
var lastRow = SpreadsheetApp.getActiveRange().getRow()-1
var col = SpreadsheetApp.getActiveRange().getColumn()
var countif=0
for (var i = lastRow; i>1; i--){
var value = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i,col).getFormula()
if (value && value.toString().charAt(0) === '=') {break}
else {if (SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i,col).getValue()==crit) {countif++} }
}
return countif
}
to automatically update the values, add reference to previous cells
=sumSinceLastFormula(F$2:F8)
when in F9, and copy where you need it.
https://docs.google.com/spreadsheets/d/1iXDbYDd_5rmHa1E41zobTWB6MKvABR1ERpCgcValIng/copy
You can calculate the cumulative by a single formula like
={"sum";arrayformula(SUMIF(ROW(A2:A),"<="&ROW(A2:A),F2:F))}

Copy Row of data based on two conditions to a sheet which is opened by ID or URL

I have a code that helps me copy a row of data based on a condition in a given column. I have a sheet called "Master" which has around 1000 rows of data. I want to move a row of data to a sheet called "Master Responses" if column 1 of "Master" has the word "Positive" or "Negative" in it. I used the or function (||) in the IF STATEMENT to select the condition (that is if "Positive" is entered or "Negative") but the row is only copied when I type "Positive" in the first column. When I type "Negative" in the first column the row is not copied. Also, I wanted to know how the code should be modified if I had to call the "Master Responses" sheet by using ".openByID or .openByURL". I have attached the code, please feel free to edit it. I am new to scripting and have been stuck on this for over a month. Any help would be appreciated. Thanks in advance.
function onEdit()
{
var sheetNamesToWatch = ["Master"];
var columnNumberToWatch = 1;
var valuesToWatch = ["Positive"];
var valuesToWatch1 = ["Negative"];
var targetSheetsToMoveTheRowTo = ["Master Responses"];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if(sheetNamesToWatch.indexOf(sheet.getName()) != -1 &&
valuesToWatch.indexOf(range.getValue()) != -1 ||
valuesToWatch1.indexOf(range.getValue()) != -1 && range.getColumn()
==columnNumberToWatch)
{
var targetSheet = ss.getSheetByName(targetSheetsToMoveTheRowTo[valuesToWatch.indexOf(range.getValue())]);
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1,
sheet.getLastColumn()).copyTo(targetRange);
}
}
I'm not sure about .openByID or .openByURL, however this should fix the problem with "Negative".
I also added extra parenthesis on the first if statement so that it was clear to me what it was checking on.
function onEdit()
{
var sheetNamesToWatch = ["Master"];
var columnNumberToWatch = 1;
var valuesToWatch = ["Positive"];
var valuesToWatch1 = ["Negative"];
var targetSheetsToMoveTheRowTo = ["Master Responses"];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getActiveCell();
if((sheetNamesToWatch.indexOf(sheet.getName()) != -1) && ((valuesToWatch.indexOf(range.getValue()) != -1) ||
(valuesToWatch1.indexOf(range.getValue()) != -1)) && (range.getColumn() ==columnNumberToWatch))
{
if (valuesToWatch.indexOf(range.getValue()) != -1)
{
var targetSheet = ss.getSheetByName(targetSheetsToMoveTheRowTo[valuesToWatch.indexOf(range.getValue())]);
}
else
{
var targetSheet = ss.getSheetByName(targetSheetsToMoveTheRowTo[valuesToWatch1.indexOf(range.getValue())]);
}
var targetRange = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
sheet.getRange(range.getRow(), 1, 1,
sheet.getLastColumn()).copyTo(targetRange);
}
}

error in google sheets script: "TypeError: function split not found in object 0. (line16, file" SplitAuto ")."

I have a script that worked before, but for a few days, this one no longer works .....
I have an error:
"TypeError: function split not found in object 0. (line16, file" SplitAuto ")."
Can you help me please?
My script :
function splitAllTest(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("RĂ©ponses au formulaire 1");
var lr=s.getLastRow();
var lc=s.getLastColumn()-8; //data columns num
var range=s.getRange(1, 3, lr, lc).getValues()
var output=[];
var split=[];
var l = 0; // outout row count
for(var i=0;i<range.length;i++){ //row roop
// split column_data
var split = [];
var max1 = 0;
for(var j=0;j<range[0].length;j++){ // column roop
var colSplit = range[i][j].split(", ");
split[j] = colSplit;
if(max1 < split[j].length) max1 = split[j].length;
}
// push new rows data
for(var k=0;k<max1;k++){ // max1
output [l] = [];
for(var j=0;j<lc;j++){ // column
if(k < split[j].length) { // if length is 1 k is only 0
output[l].push(split[j][k]); // split [col_index][coldata_index]
}else{
//output[l].push(''); change 2017/03/08 takashi
output[l].push(j == 0 ? split[j][0]: ''); //only first name is filled on each associated line
}}
l++;
}}
ss.getSheetByName("Temp formulaire").clear().getRange(1, 2,
output.length,lc).setValues(output);
}

Data Validation in code (Google Sheets)

I have the following script that runs on the 'onEdit' trigger (that part is working just fine)
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var myRange = SpreadsheetApp.getActiveRange();
if(sheet.getName() == "Plan" && myRange.getColumn() == 2 && myRange.getRow() > 3){
var option = new Array();
option[0]="0";
option[1]="1";
option[2]="2";
var dv = sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).getValidation();
dv.setAllowInvalidData(false);
dv.setHelpText("Some help text here");
dv.setCriteria(SpreadsheetApp.DataValidationCriteria.ITEM_IN_LIST,true,option );
sheet.getRange(myRange.getRow(),myRange.getColumn() + 1) .setValidation(dv);
}
}
That most of the code came from the answer on this question. Problem is that the
dv.setCriteria(SpreadsheetApp.DataValidationCriteria.ITEM_IN_LIST,true,option );
line of code doesn't work, the compiler won't even let me save it. In my looking around as to why, it seems Google has changed how it is handled, and taken their docs about it offline. Can anyone help me get this working?
yep it seems something changed...
try that:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var myRange = SpreadsheetApp.getActiveRange();
if(sheet.getName() == "Plan" && myRange.getColumn() == 2 && myRange.getRow() > 3){
var option = new Array();
option[0]="0";
option[1]="1";
option[2]="2";
// var dv = sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).getValidation();
var dv = sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).getDataValidation();
var dv = SpreadsheetApp.newDataValidation();
// dv.setAllowInvalidData(false);
dv.setAllowInvalid(false);
dv.setHelpText("Some help text here");
dv.requireValueInList(option, true);
// dv.setCriteria(SpreadsheetApp.DataValidationCriteria.ITEM_IN_LIST,true,option );
// sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setValidation(dv);
sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setDataValidation(dv.build());
}
}

Hash of a cell text in Google Spreadsheet

How can I compute a MD5 or SHA1 hash of text in a specific cell and set it to another cell in Google Spreadsheet?
Is there a formula like =ComputeMD5(A1) or =ComputeSHA1(A1)?
Or is it possible to write custom formula for this? How?
Open Tools > Script Editor then paste the following code:
function MD5 (input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
return txtHash;
}
Save the script after that and then use the MD5() function in your spreadsheet while referencing a cell.
This script is based on Utilities.computeDigest() function.
Thanks to gabhubert for the code.
This is the SHA1 version of that code (very simple change)
function GetSHA1(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, input);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
Ok, got it,
Need to create custom function as explained in
http://code.google.com/googleapps/appsscript/articles/custom_function.html
And then use the apis as explained in
http://code.google.com/googleapps/appsscript/service_utilities.html
I need to handtype the complete function name so that I can see the result in the cell.
Following is the sample of the code that gave base 64 encoded hash of the text
function getBase64EncodedMD5(text)
{
return Utilities.base64Encode( Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, text));
}
The difference between this solution and the others is:
It fixes an issue some of the above solution have with offsetting the output of Utilities.computeDigest (it offsets by 128 instead of 256)
It fixes an issue that causes some other solutions to produce the same hash for different inputs by calling JSON.stringify() on input before passing it to Utilities.computeDigest()
function MD5(input) {
var result = "";
var byteArray = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, JSON.stringify(input));
for (i=0; i < byteArray.length; i++) {
result += (byteArray[i] + 128).toString(16) + "-";
}
result = result.substring(result, result.length - 1); // remove trailing dash
return result;
}
to get hashes for a range of cells, add this next to gabhubert's function:
function RangeGetMD5Hash(input) {
if (input.map) { // Test whether input is an array.
return input.map(GetMD5Hash); // Recurse over array if so.
} else {
return GetMD5Hash(input)
}
}
and use it in cell this way:
=RangeGetMD5Hash(A5:X25)
It returns range of same dimensions as source one, values will spread down and right from cell with formulae.
It's universal single-value-function to range-func conversion method (ref), and it's way faster than separate formuleas for each cell; in this form, it also works for single cell, so maybe it's worth to rewrite source function this way.
Based on #gabhubert but using array operations to get the hexadecimal representation
function sha(str){
return Utilities
.computeDigest(Utilities.DigestAlgorithm.SHA_1, str) // string to digested array of integers
.map(function(val) {return val<0? val+256 : val}) // correct the offset
.map(function(val) {return ("00" + val.toString(16)).slice(-2)}) // add padding and enconde
.join(''); // join in a single string
}
Using #gabhubert answer, you could do this, if you want to get the results from a whole row. From the script editor.
function GetMD5Hash(value) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, value);
var txtHash = '';
for (j = 0; j <rawHash.length; j++) {
var hashVal = rawHash[j];
if (hashVal < 0)
hashVal += 256;
if (hashVal.toString(16).length == 1)
txtHash += "0";
txtHash += hashVal.toString(16);
}
return txtHash;
}
function straightToText() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var r = 1;
var n_rows = 9999;
var n_cols = 1;
var column = 1;
var sheet = ss[0].getRange(r, column, n_rows, ncols).getValues(); // get first sheet, a1:a9999
var results = [];
for (var i = 0; i < sheet.length; i++) {
var hashmd5= GetMD5Hash(sheet[i][0]);
results.push(hashmd5);
}
var dest_col = 3;
for (var j = 0; j < results.length; j++) {
var row = j+1;
ss[0].getRange(row, dest_col).setValue(results[j]); // write output to c1:c9999 as text
}
}
And then, from the Run menu, just run the function straightToText() so you can get your result, and elude the too many calls to a function error.
I was looking for an option that would provide a shorter result. What do you think about this? It only returns 4 characters. The unfortunate part is that it uses i's and o's which can be confused for L's and 0's respectively; with the right font and in caps it wouldn't matter much.
function getShortMD5Hash(input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (j = 0; j < 16; j += 8) {
hashVal = (rawHash[j] + rawHash[j+1] + rawHash[j+2] + rawHash[j+3]) ^ (rawHash[j+4] + rawHash[j+5] + rawHash[j+6] + rawHash[j+7])
if (hashVal < 0)
hashVal += 1024;
if (hashVal.toString(36).length == 1)
txtHash += "0";
txtHash += hashVal.toString(36);
}
return txtHash.toUpperCase();
}
I needed to get a hash across a range of cells, so I run it like this:
function RangeSHA256(input)
{
return Array.isArray(input) ?
input.map(row => row.map(cell => SHA256(cell))) :
SHA256(input);
}

Resources