Search code examples
google-apps-scriptgoogle-sheetschartsgoogle-visualization

Need addRange google sheet function to read backwards


I have the following code, and it works and brings me a nice chart but i want google sheet addRange function to read ranges backwards, let's say from B13 to B1 for example. Any idea how can i acomplish that?

    function newChart() {
    
          removeChartsOne("mysheet");
          const ss = SpreadsheetApp.getActiveSpreadsheet(); 
          const sheet = ss.getSheetByName("mysheet");
         
          var headerRow = sheet.getRange(1,1,1,5).getValues()
          chart = sheet.newChart()
            .setChartType(Charts.ChartType.LINE)  
            .addRange(sheet.getRange('B1:B13'))    
            .addRange(sheet.getRange('C1:C13'))    
            .addRange(sheet.getRange('D1:D13'))  
            .addRange(sheet.getRange('E1:E13'))  
            .setOption('title','Title')  
            .setOption('pointShape','circle')
            .setOption('pointSize','7')
            .setPosition(5, 5, 0, 0)  
            .setOption('series', 
             {0:{labelInLegend:headerRow[0][2]},
              1:{labelInLegend:headerRow[0][3]},
              2:{labelInLegend:headerRow[0][4]}
            })
            .build();
        
          sheet.insertChart(chart);
          
        }

Solution

  • hAxis.direction controls the direction in which the values along the horizontal axis grow. You can set it to '-1' to reverse the order of the values.

    Here's the modified part of your script:

    function newChart() {
        // ... existing code ...
    
        chart = sheet.newChart()
          // ... existing chart setup ...
          .setOption('hAxis', { direction: -1 })  // Set horizontal axis direction
          .build();
    
        sheet.insertChart(chart);
    }