r/GoogleAppsScript • • May 04 '21

Question Help migrating from Excel to Sheets... specifically need help automatically hiding/unhiding rows.

Hi folks!

I was told this is the subreddit for my problem/questions.

First, yes I have googled this. I have looked at quite a few examples but for some reason it just isn't clicking for me with the Google App Scripts coding when coming from VBA.

I have a workbook in Excel that I built. I'm proud of it. Taught myself some basic VBA to get it to do things I needed done. We have a restaurant and I am building out our catering division more. I needed to streamline processes to make things more automated and such. I built this workbook that calculates information, outputs catering quotes, outputs catering contracts, etc. I have recently realized how damn powerful Google Sheets is as well as Google App Scripts. I want to move this all out of Excel and into the Google-sphere.

I am struggling with one specific piece right now. How to hide and unhide rows in a sheet based on whether the information in a specific cell in the row is populated.

At the suggestion of another user, I threw together a small example Google Sheet for people to reference and maybe help me.

The sheet is here.

Also, I had created a small video of a screen recording to show what my excel spreadsheet does so you can see more clearly what I want to do when I move this excel workbook over to google sheets.

This is the video. It's only like 45 seconds.

In my sample Google Sheet, I want to enter quantities into the "Amount" column of the 'Calc' sheet. You will see when you do that it auto-populates that info over into the 'Output' sheet.

I used the 'Output' sheet to extract a PDF Catering Quote for the customer, so I only want to see the rows that have quantities in them and want rows of items with 0 quantities to remain hidden unless a quantity greater than 0.5 is entered for that item in the 'Calc' sheet.

I kind of show that process in the Excel workbook in the video I linked above as well.

Also, not sure if you are comfortable with VBA, but here is my code for the 'Output' sheet in Excel. It's pretty logical to follow, I think. Learned VBA on the fly to get that going. I have a lot of other spots in my Excel workbook that utilize the hiding/unhiding of rows but I feel like if I can get it nailed down in this one sheet I can figure it out with the rest of them, hopefully.

Thanks for any ideas and help!

6 Upvotes

9 comments sorted by

2

u/theiinsilence11 May 04 '21

Hey went through the same thing you did last year. I hate to be a dick but this is a chunk of code that does a little bit of what your asking.

This google doc has a menu button with a bunch of procedurally generated filter options allowing you to filter what was in a dynamically created list.

function gruntWorker(global_index) {

var ss = SpreadsheetApp.getActiveSpreadsheet(); // gets your workbook

var sheet = ss.getSheets()[1] // 1 means first sheet

//unhide all columns in row 1 ie all columns

var rCols = sheet.getRange("1:1");

sheet.unhideColumn(rCols);

//Below function returns a string array of what your trying to hide

var globalList = GetGlobalList()

//grab the filter range

var thearray = sheet.getRange(FilterColStartPoint + keywordsRow + ':' + FilterColEndPoint + keywordsRow).getValues()

//calculate the offset (of array from col 1)

var offset = col(FilterColStartPoint)

SpreadsheetApp.getUi().alert(globalList[global_index])

// loop through each cell looking for a match

for (var i = 0; i < thearray[0].length; i ++) {

//dont forget if theres a comma we got to separate them!!!!

var res = thearray[0][i].split(",");

var MatchFound = true

for (var j = 0; j < res.length; j ++) { if (res[j] === globalList[global_index]) { MatchFound = false} } // globalList index determined from function name

if (MatchFound) { sheet.hideColumns(offset + i);}

}

}

2

u/tirwander May 04 '21

Not sure why trying to help me would make you a dick lol

I'll pick through that when I get some time. Thanks!

1

u/sp3ciald3liv3ry May 05 '21

Hey there - welcome to the Google Sheets world! It's great once you get used to it. My apologies for replying without looking through the sheets you linked to, but I just recently wrote (i.e. found and repurposed) a script for just this purpose! Here it is....hope this is of some help to you!

Edit: I should mention that this code creates a custom menu with an option you can select that will auto-hide rows based on what is in Column D.

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Hide Rows')
      .addItem('Auto Hide Empty Rows', 'autoHide')
      .addToUi();
}

function autoHide() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();      // Enter sheet name
var row = s.getRange('D:D').getValues();            // Enter column letter that has the text "hide" and  "unhide"

s.showRows(1, s.getMaxRows());
for(var i=0; i< row.length; i++){ if(row[i] == 'YES') { s.hideRows(i+1, 1); }   // Value to hide
     
}}

1

u/tirwander May 05 '21

I appreciate the input! I need it to hide and unhide automatically based on values in specific cells changing when they autopopulate, though. Not a menu that I have to click to change it... is that possible? If you watch the really short video I linked, it should give you an idea. It's like 45 seconds long.

1

u/Miles_Maestro May 06 '21 edited May 07 '21

If you add this code to the example doc you shared, it should accomplish what you want. This is based off the code that u/sp3ciald3liv3ry posted above. The only difference is that this code uses the onSelectionChange simple trigger, instead of requiring you to manually click the refresh button in a custom menu.

function onSelectionChange(e) {
      if(e.range.getSheet().getSheetName() == 'Output') { // Enter sheet name
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var s = ss.getSheetByName('Output'); // Enter sheet name
        var row = s.getRange('F:F').getValues(); // Enter column letter containing values to check for "0"
        s.showRows(1, s.getMaxRows());
        for(var i=0; i< row.length; i++){ 
          if(row[i][0] === 0 || row[i][0] === "0") { // Value to hide
            s.hideRows(i+1, 1) 
          } 
        } 
      }
}

1

u/tirwander May 08 '21

Thanks for this! It gives me an error on line 2.

"TypeError: Cannot read property 'range' of undefined onSelectionChange @ Code.gs:2"

Should I specify a range before that line? And when you call 'e' in the function, what is that doing?

Also, when looking at my tester sheet. I want it to only apply the hide/unhide to rows 6:11 and 14:19... how would I throw that in there?

Thank you again!

2

u/Miles_Maestro May 09 '21

And when you call 'e' in the function, what is that doing?

The 'e' parameter is an event object that's passed to the onSelectionChange() function each time users select a new cell/range of cells in the attached spreadsheet.

Thanks for this! It gives me an error on line 2.

"TypeError: Cannot read property 'range' of undefined onSelectionChange @ Code.gs:2"

I'm guessing that you got this error when you attempted to manually run this function from the apps script code editor? If so, then this error is to be expected.

The reason being, onSelectionChange() is a special type of function in Google Apps Script. This special function is run automatically EACH time users select a new cell in the attached spreadsheet. Each time apps script triggers the function, it also passes in the Event Object that I mentioned above. The Event Object gives the function context surrounding the user's actions in the spreadsheet that triggered the function.

So this code uses the Event Object to check which sheet the user was on when the function was triggered, so that it only executes the row hiding logic if the user is on the "Output" sheet.

Also, when looking at my tester sheet. I want it to only apply the hide/unhide to rows 6:11 and 14:19... how would I throw that in there?

The code as written already accomplishes this. The code checks the sheet named "Output" for any rows that have the value "0" in column "F". Any rows that meet this criteria are hidden. The way the sheet "Output" is currently setup, no rows outside of 6:11 & 14:19 are able to have a value of "0", so they'll never be hidden.

1

u/tirwander May 10 '21 edited May 10 '21

Ok, thank for all that so far! Very helpful.

So my issue lies in the fact that I need to code to reference the cells in column C, because in my actual full spreadsheet, the 'Output' sheet looks a little different and the ===0 || ==="0" won't work in column F because some of the cells there will have text.

In my excel sheet I have it checking specific rows in column C, as I had mentioned above and if a cell ==="" (is empty) it hides it. If I do that in this code it hides EVERYTHING. That's why I was asking if there is a way to make it for specific sections of rows so I don't hide everything.

Hopefully that makes sense?

You can see in the line to my code from Excel what I did to make that happen. Wasn't sure if seeing that would help explain what I am trying to do.

Edit: So I found this line in an example elsewhere.

var range = sheet.getRange('A7:A28')

Could I do that with each of the ranges I want in the C column to get my ranges set? Then run a for loop for each? Or would I do the for loop piece differently?

Edit2: Shit, can I just list all the ranges using getRangeList?

var range = sheet.getRangeList(['C6:C11', 'C14:C19'])

Or is that not how getRangeList is used?

getRangeList didn't work, getRange for C6:C11 hid rows 2 - 6... instead of 7 - 11, when I had a value of 1 in C6. So row 6 should have been unhidden and 7-11 should have hidden... but it hid 2-6 instead. Assuming that has to do with your for loop? I use a for each loop in VBA... not sure if that would work here.

2

u/Miles_Maestro May 10 '21

Give this code a try, should do what you need.

function onSelectionChange(e) {
      if(e.range.getSheet().getSheetName() == 'Output') { // Enter sheet name
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var s = ss.getSheetByName('Output'); // Enter sheet name        
        var row = s.getRange('C:C').getValues(); // Enter column letter containing values to check for ""
        s.showRows(1, s.getMaxRows());
        for(var i=0; i< row.length; i++){ 
          if(((i >= 5 && i <= 10) || (i >= 13 && i <= 18)) && row[i][0] === "") {
            s.hideRows(i+1, 1) 
          } 
        } 
      }
}