Search code examples
google-sheets

Google Sheets Macro Script to expand column group based on cell value


I have a sheet with a column group for each week of the year. i have a formula in cell A1 that has the current week numeric value. I want to use that in a macro to determine which cell grouping should be expanded. there are 10 columns for each grouping, so the first was at cellgroup 6, 1 and the next was at 16, 11 here is what i have, but it isnt working. i would appreciate any guidance. i code in VBA but this needs to exist in Google Sheets

    function test2() {
      var spreadsheet = SpreadsheetApp.getActive();     
      var sheet = SpreadsheetApp.getActiveSheet()
      var cellValue = SpreadsheetApp.getActiveSheet().getRange('A1').getValue();
      var cellGroup = cellValue + 5
      if (cellvalue = "1") {
        spreadsheet.getActiveSheet().getColumnGroup((cellGroup), 1).expand();
      }
      else {
        spreadsheet.getActiveSheet().getColumnGroup((cellGroup+10), 1).expand();
      }
    };

here is a test sheet with the groups https://docs.google.com/spreadsheets/d/1-XwuSrn0NG8LdQV5uB3L3T0BvJ1kQufodCXq58ygO90


Solution

  • Script to expand column group based on cell value

    I modified your script and you should be able to achieve what you like using this code.


    You may try this:

    function expand() {
      var spreadsheet = SpreadsheetApp.getActiveSheet();
      var cellValue = spreadsheet.getRange('A1').getValue();
      var getRowValue = spreadsheet.getRange(1, 2, 1, spreadsheet.getLastColumn()).getValues().flat()
      spreadsheet.getColumnGroup(getRowValue.indexOf(cellValue) + 2, 1).expand()
    }
    function collapse(){
      var spreadsheet = SpreadsheetApp.getActiveSheet();
      var cellValue = spreadsheet.getRange('A1').getValue();
      var getRowValue = spreadsheet.getRange(1, 2, 1, spreadsheet.getLastColumn()).getValues().flat()
      spreadsheet.getColumnGroup(getRowValue.indexOf(cellValue) + 2, 1).collapse()
    }
    

    To use and apply this code, setup your button and assign script.

    Step 1

    Step 2


    Sample Output:

    Output


    Reference: