How to adjust google sheet view depending on variable? - google-apps-script

I have a spreadsheet with the following script that adjusts the view rows according to a variable:
function ConditionalHideRow() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form responses 1");
var maxrows = sheet.getMaxRows()
for (var i = 0; i < maxrows; ++i) {
if (sheet.getRange(maxrows-i,4).getValue() == "var1" ) {
sheet.hideRows(maxrows-i,1)
}
else
{
sheet.showRows(maxrows-i,1)
}
}
}
I want to pass a variable in the page that adjusts the view:
for example
if I pass var1 in the URL for example, the rows containing var1 are
shown, all the others are not
if I pass var2 in the URL for example,
the rows containing var2 are shown, all the others are not
etc

I have tried function doGet(e) var viewmode = e.parameter.view but doesn't seem to work when I am passing ....?view = "a"
To pass "a" to the doGet() in the URL query it like this ...?view=a; no need in the apostrophes.
Sample
function doGet(e){
var parameter = e.parameter;
if(parameter.view){ //check off the view type was passed
ConditionalHideRow(parater.view);
};
}
function ConditionalHideRow(condition){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form responses 1");
var maxrows = sheet.getDataRange().getHeight();
for (var i = 0; i < maxrows; ++i) {
if (sheet.getRange(maxrows-i,4).getValue() == condition ) {
sheet.hideRows(maxrows-i,1);
}
else
{
sheet.showRows(maxrows-i,1);
};
}
}
This is off topic, but getDataRange().getHeight() i my experience is better to use, since getMaxRows() will return you a total number of rows, even if they are empty.
By default there is a 1000 empty rows, and even though you don't have any data there, you will still loop through it. getDataRange().getHeight() will give you a number of the last row where any piece of data appears.
Also, I am just curious, why are you looping backwards through the rows?

Related

AutoFill Data with Blank Rows - Google Sheets / Google Apps Script

I have the below spreadsheet that I would like to AutoFill the persons name. the issue is that there are blank rows between the names. Each name is in line with a sku2 and needs to be inline with all locations. there can be up to 10 blank rows (due to how many locations).
if I could loop this maybe
function LoopTillLr() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A2').activate();
spreadsheet.getActiveRange().autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
spreadsheet.getCurrentCell().getNextDataCell(SpreadsheetApp.Direction.DOWN).activate();
};
Appreciate any help
If you only want to replicate the NAME values against variable LOCATION values then use this script:
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var lastRow = ss.getDataRange().getLastRow();
for (var i = 1; i < lastRow+1; i++) {
if (ss.getRange(i,1).getValue() == "") {
var value = ss.getRange(i-1,1).getValue();
ss.getRange(i,1).setValue(value);
}
}
}
Ensure that A2 is not empty else the script will fail.
If it is a lot of records, you can create a function and run it. The following does this until the end of the sheet, so make sure to delete all the rows towards the end which you do not need or adjust the range in the 2nd row.
function autoFillDown(){
const range = SpreadsheetApp.getActiveSheet().getRange("A:A");
const rows = range.getValues();
let outputArray = [];
rows.forEach( row => {
// if it contains a name, leave it
if( row[0].length > 1){
outputArray.push( [row[0]] )
// otherwise replace it with the value above it
} else {
outputArray.push( [outputArray[outputArray.length-1]] );
}
});
range.setValues( outputArray );
}

How can I check one value against another value in my Google Sheet and then query properties of the cell with the matching value?

I want to check values from a JSON URL against values within a defined range in my Google Sheet.
Should there be a match, I would like to query the properties of the cell containing the matching value (its row, its column, etc.)
How can I do this within Google Apps Script?
Everything you need to know about Spreadsheet operations in Apps Script can be found in Overview and SpreadsheetApp. You can start from there. For example, the methods to query properties like row and col are getRow and getColumn
Never mind. Got to my answer myself.
var i = 0;
// Bringing in the data from the third-party into Google Sheets.
var groupJSON = UrlFetchApp.fetch('<ANY-JSON-URL>');
var groupObjectRaw = JSON.parse(groupJSON);
// var groupObject = groupObjectRaw[0]; <--optional, for my use only
var membersGroupForm = groupObject.data['member'];
var projectsGroupForm = groupObject.data['project'];
var hoursGroupForm = groupObject.data['hours worked'];
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Details');
var membersRange = ss.getRange('Details!A:A');
var membersSheet = membersRange.getValues();
var projectsRange = ss.getRange('Details!1:1');
var projectsSheet = projectsRange.getValues();
function getRowNumber() {
for (i; i < membersSheet.length; i++) {
if (membersSheet[i][0] == membersGroupForm) {
return i + 1;
}
}
}
var rowNumber = getRowNumber(i, membersSheet, membersGroupForm);
Logger.log(rowNumber);
function getColumnNumber() {
for (var row in projectsSheet) {
for (var col in projectsSheet[row]) {
if (projectsSheet[row][col] == projectsGroupForm) {
return parseInt(col) + 1;
}
}
}
}
var columnNumber = getColumnNumber(projectsSheet, projectsGroupForm);
Logger.log(columnNumber);
var cell = ss.getRange(rowNumber, columnNumber);
cell.setValue(hoursGroupForm);

Google App Script - loops not executing

I want to create a function that will iterate over every sheet until a given sheet. The function receives the name of that last sheet as an argument.
function getUntilMonthSavings(month) {
var spreadsheet = SpreadsheetApp.getActive();
var monthSheet = spreadsheet.getSheetByName(month);
var allSheets = spreadsheet.getSheets();
var sheetNumber = monthSheet.getIndex();
var totalSavings=0;
for (var i = 1; i < monthSheet; i++){
totalSavings = totalSavings + allSheets[i].getRange("I20").getValue();
}
return totalSavings;
}
My problem is that what is returned is always 0. I've also returned i to check if it is being iterated, but it returns 1 even when the sheet index is greater than 1.
I'm sure to be doing some kind of basic blunder, but I'm quite at a loss as why this code is not working.
MonthSheet is an object and not something you can compare i to in your loop. You need the actual index of the sheet referred to.
Try:
for (var i = 0; i < monthSheet.getIndex(); i += 1) {

How to replace text in Google Spreadsheet using App Scripts?

I tried to get the value of a range and than remove all points from the cell.
var FILE = SpreadsheetApp.openById("xyz");
var CONTENT = FILE.getSheetByName("Sheet1");
var A1 = CONTENT.getRange("I17").getValue();
A1. replace(".", "");
It gives me that can't find the replace function. Is there any function in Google Apps Script that allows me to replace the string?
If this is an exact copy of your script then you have a space in-between A1. and replace but I assume it is not.
#SergeInsas is right the content needs to be a string for the replace() function to work, so if your trying to replace the . in a decimal number then you can use the toString() method first like below.
var FILE = SpreadsheetApp.openById("xyz");
var CONTENT = FILE.getSheetByName("Sheet1");
var A1 = CONTENT.getRange("I17").getValue();
var A1String = A1.toString().replace(".", "");
Or you can multiply the number to get rid of the decimal but this will depend on how many decimal places you have :)
There is a more powerful, and simpler, method available: TextFinder.
The accepted answer to this question requires an additional step to post the replaced string back to the cell.
The TextFinder method does not need you to write the data back to the cell.
And if you want to search multiple cells, then this method saves you the iterations.
var FILE = SpreadsheetApp.openById("xyz");
var CONTENT = FILE.getSheetByName("Sheet1");
var A1 = CONTENT.getRange("I17");
A1.createTextFinder(".").replaceAllWith("");
I haven't tested it on a large data set but I suspect this would be quite quick.
Edit: I wrote a short tutorial on this.
For some reason, this solution doesn't work for me. Here is my whole code that should replace the '+' symbol with 'nothing'
// I need to replace more occurrences of different strings, so this is just an example..
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange("G5:G7").getValues();
// this is a loop, to go through multiple cells that may contain the text, that needs to be replaced.
for (var i = 0 ; i<range.length ; i++) {
var le = range.length;
var stri = range[i].toString().replace("+", "");
Logger.log(stri);
}
var msg = ui.alert("Replaced?");
return msg;
Hope this help you
function removeAccents() {
var spreadsheet = SpreadsheetApp.getActive();
var range = spreadsheet.getRange("F3:F");
var data = range.getValues();
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
data[row][col] = (data[row][col]).toString().replace(/é/g, 'e');
data[row][col] = (data[row][col]).toString().replace(/ã/g, 'a');
}
}
range.setValues(data);
};
Sharing a very helpful solution from Bannager Bong on this Google Docs Editor Help Forum thread. Made a slight modification to the function so that it accepts arguments for the find, replace values and then added a range argument so that the function can target a specific region. Even so, this method is extremely slow (my sheets have 5k rows).
function Cleanup12m() {
var spreadsheet = SpreadsheetApp.getActive();
//fandr(",", "");
//fandr("\"","");
fandr("�","",spreadsheet.getRange('BA:BA')); //uses specific range
};
function fandr(find, repl) {
var r=SpreadsheetApp.getActiveSheet().getDataRange();
var rws=r.getNumRows();
var cls=r.getNumColumns();
var i,j,a,find,repl;
//find="abc";
//repl="xyz";
for (i=1;i<=rws;i++) {
for (j=1;j<=cls;j++) {
a=r.getCell(i, j).getValue();
if (r.getCell(i,j).getFormula()) {continue;}
//if (a==find) { r.getCell(i, j).setValue(repl);}
try {
a=a.replace(find,repl);
r.getCell(i, j).setValue(a);
}
catch (err) {continue;}
}
}
};
//Revised to apply to a selected range
function fandr(find, repl, range) {
var r= range;//SpreadsheetApp.getActiveSheet().getDataRange();
var rws=r.getNumRows();
var cls=r.getNumColumns();
var i,j,a,find,repl;
//find="abc";
//repl="xyz";
for (i=1;i<=rws;i++) {
for (j=1;j<=cls;j++) {
a=r.getCell(i, j).getValue();
if (r.getCell(i,j).getFormula()) {continue;}
//if (a==find) { r.getCell(i, j).setValue(repl);}
try {
a=a.replace(find,repl);
r.getCell(i, j).setValue(a);
}
catch (err) {continue;}
}
}
};

Multiple results from a single column search in a spreadsheet

I just wanted to know if there was a way to pull multiple (only 2 at the most) results with the code provided below. All the code is doing is searching for a user's name in a spread sheet and then displaying the value in the cell next to that user's name. The slight issue I'm running into now is that their name might appear twice in a given column and I would like for both results to be displayed. Any help would be appreciated. The full explanation of what this code is used for can be found here if needed: VLOOKUP style app script using UiApp and textBox form to reference a spreadsheet
// function called when submit button is clicked
function submit(e) {
var app = UiApp.getActiveApplication();
Logger.log(Utilities.jsonStringify(e)); // Log the input parameter (temporary)
// Write the data in the text boxes back to the Spreadsheet
var cell = e.parameter.userName;
var doc = SpreadsheetApp.openById('SPREADSHEET-ID');
var ss = doc.getSheets()[0];
var lastRow = doc.getLastRow();
var data = ss.getRange(2, 1, 2, 4).getValues();
var result = "User not found";
for (nn = 0; nn < data.length; ++nn) {
if (data[nn][1] == cell) {
result = data[nn][1];
break
}; // if a match in column B is found, break the loop
}
// Make the status line visible and tell the user the possible actions
app.getElementById('status').setVisible(true).setText(result);
return app;
}
All you need to do is modify the behavior of the search loop. Perform the search, adding finds to an array, and get rid of the break that was terminating a search after finding one item. At the end of the search, join the array of finds into a string, and you're done.
// function called when submit button is clicked
function submit(e) {
var app = UiApp.getActiveApplication();
Logger.log(Utilities.jsonStringify(e)); // Log the input parameter (temporary)
// Write the data in the text boxes back to the Spreadsheet
var cell = e.parameter.userName;
var doc = SpreadsheetApp.openById('SPREADSHEET-ID');
var ss = doc.getSheets()[0];
var lastRow = doc.getLastRow();
var data = ss.getRange(2, 1, 2, 4).getValues();
var result = "User not found";
var result_array = [];
for (nn = 0; nn < data.length; ++nn) {
if (data[nn][1] == cell) {
result_array.push( data[nn][1] );
}; // if a match in column B is found, keep going, there may be more!
}
if (result_array.length > 0)
result = result_array.join(", "); // concatenate multiple results
// Make the status line visible and tell the user the possible actions
app.getElementById('status').setVisible(true).setText(result);
return app;
}