不使用范围创建具有多个系列的条形图

时间:2019-10-05 16:40:57

标签: excel vba

我想知道是否有一种方法可以编写不使用Range就能创建具有多个系列(取决于输入)的条形图的宏?为了使它现在能够正常工作,在可以使用它之前,将我的输出写在一张纸上。这感觉非常不必要。还有其他方法吗?

Sub CreateBarGraph() 

Set table = Database_U.ListObjects("Table_U") '


Dim ColumnProjektID As String, ColumnVarde As String

Dim Varde As Variant, ProjektID As Variant

ColumnProjektID = "ProjektID"
ColumnVarde = "Varde"

Dim sheet As Worksheet
Set sheet = GraphSheet

Dim cht As ChartObject

Dim i As Integer
i = 1

For Each currentRow In table.ListRows

   'The return value consist of a name with letters
    Set ProjektID = RetrieveProjektID(currentRow, ColumnProjektID)    
    GraphSheet.Cells(i, 2) = ProjektID

    'The return value consist of a digit/number
    Set Varde = RetrieveVarde(currentRow, ColumnVarde)     
    GraphSheet.Cells(i, 3) = Varde

    i = i + 1

Next


Set cht = GraphSheet.ChartObjects.Add(Left:=20, Width:=800, Top:=20, Height:=500)

Dim rng As range

'1/2 of the below feels like a waste of space. I would like to find a
'way to add the source of the data (and create multiple series) 
'without writing out the values on a sheet

For j = 1 To i
    Set rng = GraphSheet.range(Cells(i, 2), Cells(i, 3))
    cht.chart.SeriesCollection.Add Source:=rng
Next i





 End Sub

是否有获得相同结果的替代方法?感谢帮助!

1 个答案:

答案 0 :(得分:1)

图表对象基本上是一个包装图表的Shape。您需要将 NewSeries 添加到 ChartObject 中包含的图表的 SeriesCollection 中。

短代码

ActiveSheet.ChartObjects(1).Chart.SeriesCollection.NewSeries.Values = Array(10, 5, 21, 54, 76, 12)

演示

Sub Test()
    Dim ChartObject As ChartObject
    Dim Chart As Chart

    Set ChartObject = ActiveSheet.ChartObjects(1)
    Set Chart = ChartObject.Chart

    Dim Series As Series
    Set Series = Chart.SeriesCollection.NewSeries

    Series.Values = Array(10, 5, 21, 54, 76, 12)

End Sub

这里是格式化系列的方式         '画线         Series.Format.Line.ForeColor.RGB = vbRed         '为内部填充物上色         Series.Format.Fill.ForeColor.RGB = vbMagenta

附录

您可以分配一个类别名称数组,如下所示:

Dim Axis As Axis
Set Axis = Chart.Axes(xlCategory)
Axis.CategoryNames = myArray2