Hide columns in various sheets in Google Sheets on open - google-sheets

I have a few scripts which, individually, all work. However I am unable to get them to all run on opening the sheet. At the moment, only the first script (hideColumn) runs on opening the sheet. The others all work when called directly from the menu I managed to create.
function onOpen() {
// get active spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// create menu
var menu = [{name: "Hide Overview Columns", functionName: "hideColumn"},
{name: "Hide Rebalancing Columns", functionName: "hideColumn2"},
{name: "Add/Hide Dividend Data for Chart", functionName: "hideColumn3"}];
// add to menu
ss.addMenu("Check", menu);
// execute function
function hideColumn(){
function hideColumn(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Overview");
// get data
var data = sheet.getDataRange();
// get number of columns
var lastCol = data.getLastColumn()+1;
Logger.log(lastCol);
// itterate through columns
for(var i=1; i<lastCol; i++) {
if(data.getCell(1, i).getValue() == 'HIDE') {
sheet.hideColumns(i);
}
}
}
function hideColumn2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Rebalancing");
// get data
var data = sheet.getDataRange();
// get number of columns
var lastCol = data.getLastColumn()+1;
Logger.log(lastCol);
// itterate through columns
for(var i=1; i<lastCol; i++) {
if(data.getCell(2, i).getValue() == 'HIDE') {
sheet.hideColumns(i);
}
}
}
function showColumn3() {
// get active spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Dividends - Calculations");
// get data
var data = sheet.getDataRange();
// get number of columns
var lastCol = data.getLastColumn();
// show all columns
sheet.showColumns(1, lastCol);
}
function hideColumn3() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Dividends - Calculations");
// get data
var data = sheet.getDataRange();
// get number of columns
var lastCol = data.getLastColumn()+1;
Logger.log(lastCol);
// itterate through columns
for(var i=1; i<lastCol; i++) {
if(data.getCell(1, i).getValue() == 'HIDE') {
sheet.hideColumns(i);
}
}
}}}

we can help but won't code for you unless you showed us you tried!
Your best option is to have a look at the Google Apps Script documentation.
Here are the pages you need to check to do your script (you'll see it's well explained)
Create a menu
Hide a column
Get the content of a range
Create a loop to check several cell one by one in JS (Mozilla Doc)

Related

How to share filtered data with same filter view in google sheets?

I am using google spreadsheet and this is my code to import data and save my filter on it.
function importCSVFromWeb() {
// Provide the full URL of the CSV file.
var csvUrl = "https://covid19.who.int/WHO-COVID-19-global-table-data.csv";
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
var csvData = Utilities.parseCsv(csvContent);
var sheet = SpreadsheetApp.getActiveSheet();
// --- I added below script.
var filter = sheet.getFilter();
var range = filter.getRange();
var criteria = [];
var start = range.getColumn();
var end = start + range.getNumColumns() - 1;
for (var i = start; i <= end; i++) {
var criterion = filter.getColumnFilterCriteria(i);
if (criterion) criteria.push({col: i, c: criterion.copy()});
}
filter.remove();
// ---
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
// And, I added below script.
criteria.forEach(({col, c}) => range.createFilter().setColumnFilterCriteria(col, c));
}
My issue is: How can i share the spreadsheet with my filter applied on it to use it ?
In my case, I want to use another visualization tool on only filtered data

Deleting Row Based on Cell Values

I am attempting to create a additional menu option that allow me to automatically delete all rows that contain the text "Complete" in Column D. The script I have runs and finishes with no errors but does not delete the rows. I tried to find help on line and tweaked the code but same result
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 'Complete';
for (var i = 'Complete'; i <= numRows - 1; i++) {
var row = values[i];
if (row[2] == 'Complete' || row[2] == '') {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Delete Rows where column shows Complete Text",
functionName : "readRows"
}];
sheet.addMenu("Script Center Menu", entries);
};

Google Sheets script to ignore or include specific sheets

I am getting this error: TypeError: Cannot call method "getName" of null. I have used a script to replace the formulas of the active sheet with the cell values. However, I don't want to accidentally run this on a few sheets, so I want to be able to exclude or include only specific sheets. I have been following another post and came up with this, and now I have the error:
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
//loop through all sheets and get name to see if it includes specific string
for (i = 0; i < sheets.length; i++) {
var sheet = ss.getSheetByName(sheets[i]);
var name = sheet.getName();
if (name.includes("String_00")) {
//get active sheet and replace range with values
var sheetActive = ss.getActiveSheet();
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
} else {
continue;
//skip over all those that don't meet the condition
}
}
}
UPDATE:
Trying this:
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
//loop through all sheets and get name to see if it includes specific string
for (i = 0; i < sheets.length; i++) {
//var sheet = ss.getSheetByName(sheets[i]);
var name = sheets[i].getName().toString();
if (name.indexOf("String_00") > -1) {
//get active sheet and replace range with values
//var sheetActive = ss.getActiveSheet();
var range = sheets.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
} else {
continue;
//skip over all those that don't meet the condition
}
}
}
But now it doesn't do anything. using .include was giving me an error, so I moved over to .indexOf() > -1. Does not freeze data as expected for any sheet, regardless of name.
I came up with 2 solutions for this, sort of started from the drawing board. One creates an array, a sort of blacklist, and then if the sheet name contains any item in the blacklist, then it returns and doesn't execute the replacement. The second solution searches for a pattern in the sheet name and only then continues on to the replacement. Both accomplish what I was trying to do. I think the code I found was a bit buggy and was a bit complicated for what I was doing. I didn't need to loop through all sheet names, just check the sheet name against given variables. Anyway, here they are:
This one creates the array blacklist of pages not to edit:
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4'];
var sheetActive = ss.getActiveSheet();
if (sheets.indexOf(sheetActive.getName()) > -1) return;
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
}
This one only searches for specific text in the sheet name before proceeding with the replacement.
function freezeValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetActive = ss.getActiveSheet();
var name = sheetActive.getName()
if (name.indexOf("String_00") > -1) {
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
}
}
I'm sure there is a method to use sheet index value so if you want to skip the first 4 sheets, you can probably do that as well, so it doesn't call on names at all.
UPDATE
function freezeValues2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetActive = ss.getActiveSheet();
if (sheetActive.getIndex() > 4) {
var range = sheetActive.getRange("A1:Z50");
range.copyTo(range, {contentsOnly: true});
}
}

Wanting auto sort on 3 sheets, when one is locked

Please see the previous post on this question;
Auto Sort not working on Multiple Sheets within one Google Sheet
Here's the good script from that last session;
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = event.source.getActiveSheet().getName()
var editedCell = event.range.getSheet().getActiveCell();
if(sheet=="Loan Inquiries"){
var columnToSortBy = 2;
var tableRange = "A3:G99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}}
else if(sheet=="Deals in Escrow"){
var columnToSortBy = 7;
var tableRange = "A3:I99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var tableRange = "A3:I99"; //range to be sorted
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
else{return}
}}
function test_onEdit() {
onEdit({
user : Session.getActiveUser().getEmail(),
source : SpreadsheetApp.getActiveSpreadsheet(),
range : SpreadsheetApp.getActiveSpreadsheet().getActiveCell(),
value : SpreadsheetApp.getActiveSpreadsheet().getActiveCell().getValue(),
authMode : "LIMITED"
});
}
This thread successfully resolved my question, however, now what I want to do is to Auto Sort a 3rd Sheet, which is locked to others, but not to myself. The 3rd Sheet will be titled "Karlan Production for 2017". I also want this 3rd sheet to pull all new data from the 2nd Sheet "Deals in Escrow" and in the same formatting as the 2nd Sheet and to auto sort as the data is imported to the 3rd Sheet, but also be able for me to input new deals manually as well in the 3rd Sheet and still be able to auto update.
I believe this will do what you want:
function onEdit(event){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = event.source.getActiveSheet().getName()
var editedCell = event.range.getSheet().getActiveCell();
if(sheet=="Loan Inquiries"){
var columnToSortBy = 2;
var tableRange = "A3:G99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}}
else if(sheet=="Deals in Escrow"){
var columnToSortBy = 7;
var tableRange = "A3:I99"; //range to be sorted
if(editedCell.getColumn() == columnToSortBy){
var range = ss.getActiveSheet().getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
combineData()
}}
else if(sheet=="Karlan Production for 2017"){
var columnToSortBy = 7;
if(editedCell.getColumn() == columnToSortBy){
combineData()
}}
else{return}
}
function combineData(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheets()[1]
var lr = s.getLastRow()
var s1=ss.getSheets()[2]
var lr1 = s1.getLastRow()
var lc1=s1.getLastColumn() //get the last column of 'Karlan Production for 2017'
var rng=s.getRange(3, 1, lr,lc1).getValues() //get 'Deals in Escrow' values
var rng1=s1.getRange(3, 1, lr1,lc1).getValues() //get 'Karlan Production for 2017' values
var rng2=[]
var rng2=rng.concat(rng1) //combine 'Deals in Escrow' and 'Karlan Production for 2017' values (all rows)
removeDuplicates(rng2) // call remove duplicates sending combined array
}
function removeDuplicates(data) {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var s1=ss.getSheets()[2]
var newData = new Array();
for(i in data){
var row = data[i];
var duplicate = false;
for(j in newData){
if(row.join() == newData[j].join()){
duplicate = true;
}
}
if(!duplicate){
newData.push(row);//create array of non duplicate rows
}
}
s1.clearContents(); //clear 'Karlan Production for 2017'
var sor=s1.getRange(3, 1, newData.length, newData[0].length).setValues(newData); //set new array
sor.sort( { column : 7, ascending: true } );//sort new data
}
After adding the new sheet, click the arrow on the sheet tab.
Click Protect Sheet. In the popup, enter a description and click
the Sheet button. Click the Set permissions button. In the Range
editing permissions popup click the arrow by 'Only you'. Select
'Custom' and add the email address of the other person you want
to be able to edit the sheet. Click done.

Removing a row in sheet 2 from imported data from sheet 1 in google spreadsheet

screenshot
Hi all, i need help and i am not a coder. I am trying to achieve the same thing on sheet number 2.
My datas are imported through "=Submission!$b2" from sheet 1
i need help removing rows automatically when a specific cell on column H does not contain the value "Bekreft", i tried both codes shown here with no success.
This is what i added for script:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('DATA - Do Not Touch!!!'); // change to your own
var values = s.getDataRange().getValues();
for(var i=values.length;i>0;i-=1){
var lcVal=values[i-1][0].toLowerCase() //Change to all lower case
var index = lcVal.indexOf("vent"); //now you only have to check for contains "vent"
if (lcVal.indexOf("vent") > -1){
s.deleteRow(i)};
}}
Seeing as you state you are "not a coder", and the code you pasted will not help you if you are referencing data from another page, I would suggest using a filter function to achieve your goal. You would add the following formula to your second page:
=FILTER(Submission!B:B,ISNUMBER(SEARCH("Bekreft", Submission!H:H)))
If you are looking to have a script go through your static list and delete out values that do not contain "Bekreft" then you can use the following script.
function onEdit() {
var sheet = SpreadsheetApp.openById("Add Sheet ID").getSheetByName('Sheet1');
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
//row for condition
if (row[7].indexOf("Bekreft")) {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
};

Resources