Here’s an example of an OfficeScript that adds a chart to a worksheet in an existing workbook:
function main(worksheet: ExcelScript.Worksheet) { // Define the range of data for the chart let dataRange = worksheet.getRange("A1:B5"); // Add a chart to the worksheet let chart = worksheet.addChart(ExcelScript.ChartType.ColumnClustered, dataRange); // Set the title of the chart chart.setTitle("Sample Chart"); // Set the x-axis and y-axis titles chart.setXAxisTitle("X-Axis"); chart.setYAxisTitle("Y-Axis"); }
To use this OfficeScript, follow these steps:
- Open Excel Online or Excel for the web.
- Open an existing workbook.
- Select the worksheet where you want to add the chart.
- Click on the “Automate” tab in the ribbon.
- Click on the “Script Lab” button.
- In the Script Lab pane, create a new script or open an existing one.
- Replace the default code in the script editor with the code provided above.
- Click the “Run” button to execute the script.
This script adds a column clustered chart to the worksheet, using the data range specified in the getRange
function. You can modify the range and chart type according to your needs. Additionally, you can set the title, x-axis title, and y-axis title of the chart using the provided functions.
Please note that OfficeScripts are currently only supported in Excel for the web and Excel Online. They are not available in the desktop version of Excel.