如何解决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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。