OfficeScripts currently does not support direct interaction with charts in Excel. Therefore, there is no built-in function to check if a chart exists with a specific name.
However, you can use a workaround to check if a chart with a given name exists by iterating through all the charts in the workbook and comparing their names. Here’s an example of how you can achieve this:
function checkChartExists(chartName) { // Get the active workbook var workbook = context.workbook; // Get the worksheets collection var worksheets = workbook.worksheets; // Iterate through all worksheets to find the chart with the given name for (var i = 0; i < worksheets.getCount(); i++) { var worksheet = worksheets.getItemAt(i); var charts = worksheet.charts; // Iterate through all charts in the worksheet for (var j = 0; j < charts.getCount(); j++) { var chart = charts.getItemAt(j); // Check if the chart name matches the given name if (chart.name === chartName) { return true; // Chart exists } } } return false; // Chart does not exist }
In this example, the checkChartExists
function takes a parameter chartName
, which represents the name of the chart you want to check for existence. The function iterates through all the worksheets in the workbook and then through all the charts in each worksheet. It compares the chart name with the provided chartName
using chart.name === chartName
. If a match is found, the function returns true
, indicating that the chart exists. If no match is found, the function returns false
, indicating that the chart does not exist.
To use this function, you can call it with the desired chart name as an argument. For example:
checkChartExists("Chart1") .then(function (chartExists) { console.log("Chart exists: " + chartExists); }) .catch(function (error) { console.log("Error occurred: " + error); });
Please note that this workaround iterates through all the charts in the workbook, so it may not be efficient for workbooks with a large number of charts. Additionally, keep in mind that OfficeScripts are only supported in Excel for the web and Excel Online, and they may have limitations compared to other programming environments.