1

I cannot figure out how to delete charts with VBA.

Starting Point:

  1. Create Blank Workbook
  2. Press F11 three times to create Chart1, Chart2, and Chart3
  3. Right-click in Chart2, Move Chart, Object in: Chart 1
  4. Right-click in Chart3, Move Chart, Object in: Chart 1

What VBA code will delete all charts (Chart2 and Chart3) from Chart1?

Attempts:

'Try 1: Run-time error -2147024809 (80070057):
'        The specified value is out of range.
Sheets("Chart1").ChartObjects.Delete

'Try 2: (Same error)
Charts("Chart1").ChartObjects.Delete
4

1 回答 1

2

您似乎无法删除该图表。原因是图表被锁定,无法从 VBA 或应用程序中解锁它。

我想出的唯一解决方法是:1.将其移至任何工作表,2.将其删除。

可能的代码如下:

Dim myCHART As Chart
Set myCHART = Sheets("Chart1")


myCHART.ChartObjects(1).Select
ActiveChart.Location Where:=xlLocationAsObject, Name:=Worksheets(1).Name
Worksheets(1).Shapes(Worksheets(1).Shapes.Count).Delete

更新代码:(由史蒂文)

Do While Charts("Chart1").ChartObjects.Count > 0
    Charts("Chart1").ChartObjects(1).Chart.Location xlLocationAsObject, _
                                                    Worksheets(1).Name
    Worksheets(1).Shapes(Worksheets(1).Shapes.Count).Delete
Loop
于 2013-05-30T17:01:58.320 回答