Search code examples
arraysexcelvbagraph

VBA Excel - Create pie chart from 2 dimensional array


I am trying to create a chart from calculated values in a procedure The first part of the procedure creates an Array (Variant) called "varUnique"

Let says for example it has the following values:

varUnique(0,1)="Houses"
varUnique(0,2)="Buildings"
varUnique(0,3)="Parkings"
varUnique(1,1)=4
varUnique(1,2)=3
varUnique(1,3)=9

I would like to create a new graph sheet that shows the previous

My code:

Set new_chart = Charts.Add()
    With new_chart
        .ChartType = xlPie
        .SeriesCollection.NewSeries
        .SeriesCollection(1).XValues = varUnique(0)
        .SeriesCollection(1).Values = varUnique(1)
    End With

generates a runtime error '9' : subscript out of range at the .SeriesCollection(1).XValues = varUnique(0) step

Can anyone help please ?


Solution

  • You can use Index. Note that Index is one-based.

    .SeriesCollection(1).XValues = Application.Index(varUnique, 1)
    .SeriesCollection(2).Values = Application.Index(varUnique, 2)
    

    Output:

    enter image description here