I am trying to count visible columns in a spreadsheet with no luck. I've been trying using SUBTOTAL function but it's applied to hidden/visible rows only. I also tried working with CELL("width") function, but it doesn't return 0 when a cell is hidden
Is there any other option to ignore hidden columns in a count formula?
You can definitely create your own custom function using Google Apps Script.
For example, the following function counts the number of visible columns in your active sheet:
function countVisibleColumns() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
var n_cols = sheet.getMaxColumns();
var hidden_cols = []
var cnt = 0;
for (var i=1; i<=n_cols ; i++) {
if ( sheet.isColumnHiddenByUser(i) ){
continue;}
else {cnt +=1} }
Logger.log(cnt)
return cnt;
}
You just need to click on Tools => Script editor and then copy the aforementioned code into a blank script. Then you can directly use the function as a formula in the google sheet like =countVisibleColumns().
See screenshot attached for more information.
Related
I am trying to do a SUM of last 12 rows in the column (I'll be adding more rows into this column so I wanted to automate the calculation).
First of all, I am able to get the value of last cell with some value in this column by =SUMPRODUCT(MAX((B1:B200<>"")*ROW(B1:B200))) - result is stored in C1. However, I am not sure how to use this value inside the SUM formula, I was thinking something like =SUM(B(get value of C1)-12:B(get value of C1).
I tried multiple things but none of them have worked - I also don't mind using a different approach if it gets the job done.
You can create your own custom function to do that using Google Apps Script (GAS).
Try the following:
function onEdit(e){
var row = e.range.getRow();
var col = e.range.getColumn();
if ( col==2 && e.source.getActiveSheet().getName() == "Sheet1" ){
e.source.getActiveSheet().getRange("C1").setValue(sumLast12());
}
}
function sumLast12() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
var sheet_size = sheet.getLastRow();
var elmt = sheet.getRange("B1:B"+sheet_size).getValues().flat([1]);
var elmt12 = elmt.slice(-12);
var sum = 0;
for( var i = 0; i < elmt12.length; i++ ){
sum += parseInt( elmt12[i], 10 );
}
return sum;
}
Explanation:
In order to activate this functionality go the menu bar on top of the
spreadsheet file and click on Tools => Script editor and copy the
aforementioned code into a blank script document (see attached
screenshot for more information) and save the document (cntrl+s).
After the script has been saved, everytime you edit a cell in column
B (either by adding a new value on the bottom or modify an existing value, the script will automatically update the value in
cell C1 with the sum of the last 12 values in column B.
Note that if you don't want to change my code, name the sheet you are working with as Sheet1.
Does this work?
=SUM(FILTER(B:B,ROW(B:B)>=MAX(ROW(B:B))-12)
I am trying to write a formula that counts the number of times the number 1 appears in cell F1 of all my sheets. My sheets have varying names (18-0100, 18-0101, 18-0102...). I tried the following formula:
=COUNTIF(INDIRECT("'"&"'!F1"),"=1")
It acts unpredictably. It will only return 1 even if it should be more than 1. And when I try to start trying to count 2 instead of 1 it returns 0 and not the correct number.
What am I doing wrong?
Your formula counts only the current sheet.
To get them all you need to enter all sheet names:
The formula for each sheet is:
=(INDIRECT("'"& sheet_name &"'!F1")=1)*1
You can leverage a Google Apps Script to pull this off as well.
From your spreadsheet, go to Tools > Script Editor. Add the code below, then save. The function saved there will be accessible by all other Google apps, including your spreadsheet. You can then use the name of the function in your spreadsheet like you would with any other formula.
function OccurrencesInSheetNames(str) {
var c = 0;
var regExp = new RegExp('[' + str + ']', 'g');
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sheetnames = [];
for (var i=0; i<sheets.length; i++) {
sheetnames.push([sheets[i].getName()]);
}
for (var i=0; i<sheetnames.length; i++) {
var name = sheetnames[i].toString();
var count = (name.match(regExp) || []).length;
c += count;
}
return c;
}
Now in your cell F1, place the following formula:
=OccurrencesInSheetNames(TEXT(1,0))
You can also replace the 1 in the above formula with a cell reference, if that works better for your needs. (e.g. =OccurrencesInSheetNames(TEXT(C5,0)) if you want to search through your sheet names for the integer number found in cell C5.)
Here's a demo spreadsheet for you to try out.
I made some 'conditional formatting' in Google Sheets for one sheet but I need to apply to others. There are about 45 tables and I really don't want to copy-paste it. Can anyone help me with that?
A quick solution would be to do the following:
Record a macro of how you apply the conditional formatting on the first sheet
Edit the macro so that it loops through each sheet (see code example below)
Be sure to do this on a copy of the original sheet first in case there are any issues
Code:
function autoConditionalFormat() {
// Counts how many sheets there are
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
numSheets = sheets.length;
// Loop to get name of each tab (sheet)
var tabNames = new Array()
for (var i=0; i<numSheets; i++) tabNames.push( [ sheets[i].getName() ] )
// Loops through each sheet
for (var i = 0; i < numSheets; i++) {
// Applies some conditional formatting to each sheet
SpreadsheetApp.setActiveSheet(ss.getSheetByName(tabNames[i]));
// Insert what your macro recorded here:
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A2').activate();
var conditionalFormatRules = spreadsheet.getActiveSheet().getConditionalFormatRules();
conditionalFormatRules.push(SpreadsheetApp
.newConditionalFormatRule()
.setRanges([spreadsheet.getRange('A2')])
.whenCellNotEmpty()
.setBackground('#B7E1CD')
.build());
spreadsheet.getActiveSheet()
.setConditionalFormatRules(conditionalFormatRules);
}
}
}
I have a google sheet that I would like to have generate an email alert when one column is greater than the other. Specifically, column F > column G. Here is what I have so far, any advice would be greatly appreciated, as I do not have much skill writing functions.
function readCell() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Watch list");
var value = sheet.getRange("F2").getValue();
var value1 = sheet.getRange("G2").getValue();
if(value>value1) MailApp.sendEmail('example#gmail.com', 'subject', 'message');
};
Currently this only attempts to compare cell F2 to cell G2. Is there a way to make the function compare the entire F column against column G, and generate an email for each individual case where Fx > Gx ?
Thank you!!
You have to loop all over the range.
first instead of getting the content of one cell you'll need to get the content of all the column:
var value = sheet.getRange("F2").getValue();
become that
var values = sheet.getRange("F2:F").getValues();
(same for value1)
then you need to create an empty table that will collect the results:
var results = [];
and now you need to loop throught all the values:
for(var i=0;i<values.length;i++){
//do the comparaison and store result if greater for example
}
then you may send the result.
all put together it give something like that:
function readCell() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Watch list");
var values = sheet.getRange("F2:F").getValues();
var value1s = sheet.getRange("G2:G").getValues();
var results = [];
for(var i=0;i<values.length;i++){
if(values[i]<value1s[i]){
results.push("alert on line: "+(i+2)); // +2 because the loop start at zero and first line is the second one (F2)
}
}
MailApp.sendEmail('example#gmail.com', 'subject', results.join("\n"));
};
If you want to trigger that function automatically you'll also need to change the way you call the spreadsheet (instead of getActive.... you'll need to use openById)
Let I have two column, A and B . How I can find duplicates of this two column combination?
As shown in the picture, duplicate of combination of two column will be colored.
You can get the duplicates highlighted, with the help of following script:
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{name : "Check Duplicates",functionName : "duplicates"}];
sheet.addMenu("Scripts", entries);
};
function duplicates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var r = s.getRange("A:B");
var v = r.getValues();
r.setBackground('white');
var f = r.getBackgrounds();
var lastrow = getLastPopulatedRow(v);
for( var i=0;i<lastrow;i++){
for( var j=i+1;j<lastrow;j++){
if( ( v[i][0]==v[j][0] && v[i][1]==v[j][1] ) || ( v[i][0]==v[j][1] && v[i][1]==v[j][0] ) ) {
f[i][0]='lightgreen';
f[i][1]='lightgreen';
f[j][0]='lightgreen';
f[j][1]='lightgreen';
}
}
}
r.setBackgrounds(f);
};
function getLastPopulatedRow(data) {
for (var i=data.length-1;i>=0;i--)
for (var j=0;j<data[0].length;j++)
if (data[i][j]) return i+1;
return 0;
};
Run the function "duplicates" from the script editor. You will also be able to run it from the custom menu "Scripts" from your spreadsheet.
Here is the Screenshot
I think #jwilson gave the proper answer.
However, here is a shortcut method, it may help you.
Select a cell and use CONCATENATE function to join two column value with a space between them. Then you can search the current column if they have duplicates.
For example, using your example image, select your column C1 and add =CONCATENATE(A1," ",B1) and drag this to applicable the formula for all cells in column C. Then add a conditional format rules for column C to check duplicates using =countif(C:C,C1)>1.
Here what is happening is, value of column A and B is concatenating first, then compared if those have duplicate entry in the record.
Use the following Custom formula for Conditional formatting:
=countif(arrayformula($A:$A&"|"&$B:$B);$A1&"|"&$B1)>1