Excel VBA 如何使用 Chartobjects 对象?

问题描述

我正在尝试使用图表对象对象收集图表对象,但我不确定需要使用什么方法来更改图表对象内的图表。

这是我想要的一般代码结构:

dim ExampleChart as chartobject
dim ChartCollection1 as chartobjects
dim ChartCollection2 as chartobjects

set ExampleChart = Activesheet.ChartObjects.Add( 0,400,300)
set ChartCollection2 as Activesheet.ChartObjects

'add ExampleChart to ChartCollection1 ?
'remove ExampleChart from ChartCollection2 ?

解决方法

图表重组示例如下:

Option Explicit

Sub ReGroupCharts()
    Dim shpGroup As Shape
    Dim ch(1 To 5) As String,i As Integer,j As Integer
    Dim a()
    
    '1st phase - group
    
    ActiveSheet.Range("A1").Select  'error occurs if selected non-contiguous cells
    For i = LBound(ch) To UBound(ch)
        'create 5 charts with shift
        ch(i) = ActiveSheet.ChartObjects.Add(i * 50,i * 50,400,300).Name
    Next
    ' group them
    Set shpGroup = ActiveSheet.Shapes.Range(ch).Group

    '2nd phase - regroup
    
    ReDim a(1 To 3)
    j = 1
    For i = LBound(ch) To UBound(ch)
        If i Mod 2 = 1 Then
            a(j) = ch(i)        ' select odd elements into array a() from array ch()
            j = j + 1
        End If
    Next i
    
    shpGroup.Ungroup    'ungroup initial group
    
    'make group with chart names from a()
    Set shpGroup = ActiveSheet.Shapes.Range(a).Group
    
    ' shift new group right
    shpGroup.Left = shpGroup.Left + 300
End Sub

第一阶段后
enter image description here

第二阶段后
enter image description here