Delete Excel Chart
c#, charts, excel
Solution
In Excel make sure that the Chart actually exists with the name.
You can rename a chart using
Sheets("Sheet1").ChartObjects(1).Name = "Chart01"
then when you click on the chart in the spreadsheet view you can see that it actually renamed
On the C# side I would suggest a minimal example like this
bool deleted = false;
try
{
ChartObject myChart = ws.ChartObjects("Chart01");
myChart.Delete();
deleted = true;
}
catch
{
MessageBox.Show("Chart with this name could not be found");
//throw new Exception("Chart with this name could not be found");
}
finally
{
MessageBox.Show("the chart was " + (deleted ? "deleted" : "not deleted"));
}
Problem
I want to delete a Chart from an Excel file. The Excel file is an automatically generated historyfile with a chart, the problem is, that every time I renew the history, it makes a new chart, but the old one must be deleted... This is my code: ``` Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(path); ExcelApp.Visible = true; Excel.Worksheet Sheet = (Excel.Worksheet)ExcelWorkBook.Worksheets.get_Item(1); Excel.Range range = Sheet.UsedRange; int i = 2; while (Convert.ToString((range.Cells[i, 1] as Excel.Range).Value2) != null) { i++; } Excel.Range oRange; Excel._Chart oChart; Excel.Series oSeries; oChart = (Excel._Chart)ExcelWorkBook.Charts.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value); oRange = Sheet.get_Range("A2:H" + i).get_Resize(Missing.Value, 8); oChart.ChartWizard(oRange, Excel.XlChartType.xlLineStacked, Missing.Value, Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,"Chart01"); oSeries = (Excel.Series)oChart.SeriesCollection(1); oSeries.XValues = Sheet.get_Range("A2", "A" + i); oChart.Location(Excel.XlChartLocation.xlLocationAsObject, Sheet.Name); ``` Now I need to delete the existing Chart before that code. Something like ``` Excel._Chart asdf = Sheet.ChartObjects("Chart01").Chart; if (asdf != null) { asdf.Delete(); } ``` This doesn't find a chart with name "Übersicht" but there is a chart with title "Übersicht" EDIT: The Problem now is that it can't delete the Chart: Exception from HRESULT: 0x800A03EC