How to update the data range of an existing graph using app script? [Google Sheets]

这一生的挚爱 提交于 2020-02-25 05:18:25

问题


I have created the script below, which runs from an onedit function for when cell J1 is edited. The graph exists in the sheet titled 'Daily Data'. The data it will be using is from a sheet titled 'Long Term Data'.

I used the following link as guidance: https://developers.google.com/apps-script/reference/spreadsheet/embedded-chart.

Thank you for any help.

function onEdit(e) {

  //This IF statement ensures it will only run when cell J1 is edited:
  if (
    e.source.getSheetName() == "Daily Data" &&
    e.range.columnStart == 10 &&
    e.range.columnEnd == 10 &&
    e.range.rowStart >= 1 &&
    e.range.rowEnd <= 1 
  ) { 

    var spreadsheet = SpreadsheetApp.getActive();
    var daily_data = spreadsheet.getSheetByName("Daily Data");
    var LTD_data = spreadsheet.getSheetByName("Long Term Data");

       //ABOVE HAS BEEN TESTED AND RUNS SUCCESFULLY. THE BELOW DOES NOT...

    var chart = daily_data.getCharts()[0];
    var range = LTD_data.getRange("B2:J3")
    chart = chart.modify()
        .addRange(range)
        .build();
    spreadsheet.updateChart(chart);
  }
}
;

回答1:


  • You want to update chart in the sheet of Daily Data using Google Apps Script.

If my understanding is correct, how about the following modification?

Modification point:

  • updateChart() is the method of Class Sheet. But in your script, updateChart() is used for Class Spreadsheet. By this, the script doesn't work.

When above point is reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, the range is added to the existing ranges.

Modified script:

From:
spreadsheet.updateChart(chart);
To:
daily_data.updateChart(chart);

Pattern 2:

In this pattern, the existing ranges are removed and new range is added.

Modified script:

From:
var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")
chart = chart.modify()
    .addRange(range)
    .build();
spreadsheet.updateChart(chart);
To:
var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")
var ranges = chart.getRanges();
chart = chart.modify();
ranges.forEach(function(range) {chart.removeRange(range)});
var modifiedChart = chart.addRange(range).build();
daily_data.updateChart(modifiedChart);

Note:

  • In above case, the simple trigger of OnEdit event trigger can be used.

References:

  • updateChart(chart)
  • removeRange(range)

If I misunderstood your question and this was not the result you want, I apologize.



来源:https://stackoverflow.com/questions/60226171/how-to-update-the-data-range-of-an-existing-graph-using-app-script-google-shee

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!