I created a chart within a Google Sheets document and now I want to copy it. While there is a user interface option for chart duplication, I attempted to achieve this through Google Apps Script but didn’t succeed. Here’s my script attempt:
function replicateChart() {
var currentSheet = SpreadsheetApp.getActiveSheet();
var originalChart = currentSheet.getCharts()[0];
var newChart = currentSheet.newChart();
newChart = originalChart;
currentSheet.insertChart(newChart);
}
What modifications do I need to make to this script in order to effectively duplicate the first chart in my spreadsheet?
The issue here primarily revolves around how JavaScript objects work. When you attempt to assign originalChart to newChart, you are copying the reference to the chart, not the chart itself. Google Apps Script does not provide a direct method to duplicate charts, but you can clone the chart builder with the copy() method. Here’s a modified version:
function replicateChart() {
var currentSheet = SpreadsheetApp.getActiveSheet();
var originalChart = currentSheet.getCharts()[0];
var chartBuilder = originalChart.modify().copy();
var newChart = chartBuilder.build();
currentSheet.insertChart(newChart);
}
This approach should effectively create and insert a copy of the first chart into the spreadsheet.
i’ll add that you might also consider manually post-editing, if the charts have different positions or don’t perfectly replicate properties. sometimes script-generated charts need a bit of tweaking by hand in sheets. if you run into issues, the UI could help adjust any misalignment errors.