Excel VBA 'dim as Variant' 不允许'for each' 循环

问题描述

我的代码陷入了困境。我正在尝试删除占据同一合并单元格的图表,但出现错误。如果未将剪贴图设置为变体,则代码将无法编译 for each ScrapChart in AllChartsInBox(),但随后我在尝试运行 ScrapChart.delete 时收到运行时错误 91。

为什么 Scrapchart 必须设置为变体,而 SheetChart 在设置为 ChartObject 时在 For Each SheetChart In Ws_Charts.ChartObjects 循环中工作正常?

option explicit
Dim NumberofChartsinRange,ChartBoxIndex As Long
Dim SheetChart,AllChartsInBox() As ChartObject
Dim ScrapChart As Variant

Set ChartBox = Ws_Charts.Range("A1:F6")
Ws_Charts.Cells(1,1).Formula2 = formulastring

ChartBox.Merge
ChartBox.HorizontalAlignment = xlRight
ChartBox.VerticalAlignment = xlBottom

NumberofChartsinRange = 0

If Ws_Charts.ChartObjects.Count = 0 Then

Else

    ReDim AllChartsInBox(Ws_Charts.ChartObjects.Count - 1)
    
    For Each SheetChart In Ws_Charts.ChartObjects
        If Not Intersect(SheetChart.TopLeftCell,ChartBox) Is nothing Then
            NumberofChartsinRange = NumberofChartsinRange + 1
            Set AllChartsInBox(ChartBoxIndex) = SheetChart: ChartBoxIndex = ChartBoxIndex + 1
        End If
    Next
End If

If NumberofChartsinRange > 1 Then
    For Each ScrapChart In AllChartsInBox
        ScrapChart.Delete
    Next ScrapChart
End If

解决方法

您可以一次性完成 ChartObjects 集合:

Dim SheetChart,co As ChartObject,ChartBox As Range
Dim tmp As ChartObject,foundOne As Boolean,i As Long

Set ChartBox = Ws_charts.Range("A1:F6")
Ws_charts.Cells(1,1).Formula2 = formulastring

ChartBox.Merge
ChartBox.HorizontalAlignment = xlRight
ChartBox.VerticalAlignment = xlBottom

For i = Ws_charts.ChartObjects.Count To 1 Step -1
    Set co = Ws_charts.ChartObjects(i)
    If Not Intersect(co.TopLeftCell,ChartBox) Is Nothing Then
        If Not foundOne Then 'first chart found?
            Set tmp = co
            foundOne = True
        Else
            'multiple charts - delete the first one and this one...
            If Not tmp Is Nothing Then tmp.Delete
            co.Delete
        End If
    End If
Next i