Create Chart from Array data and not range Create Chart from Array data and not range vba vba

Create Chart from Array data and not range


Yes. You can assign arrays to the XValues and Values properties of a Series object on a chart. Example:

Dim c As ChartDim s As SeriesDim myData As VariantSet c = ActiveChart ' Assumes a chart is currently active in Excel...Set s = c.SeriesCollection(1)myData = Array(9, 6, 7, 1) ' or whatevers.Values = myData


You can assign arrays to chart series in Excel 2007 onwards but in previous versions I believe there is a 255 character limit for the length of each series. A method I have used to work around this restriction is shown in the following random walk example:

Sub ChartArray()Dim x(0 To 1000, 0 To 0) As DoubleDim y(0 To 1000, 0 To 0) As Doublex(0, 0) = 0y(0, 0) = 0For i = 1 To 1000    x(i, 0) = i    y(i, 0) = y(i - 1, 0) + WorksheetFunction.NormSInv(Rnd())Next iCharts.AddActiveChart.ChartType = xlXYScatterLinesNoMarkersWith ActiveChart.SeriesCollection    If .Count = 0 Then .NewSeries    If Val(Application.Version) >= 12 Then        .Item(1).Values = y        .Item(1).XValues = x    Else        .Item(1).Select        Names.Add "_", x        ExecuteExcel4Macro "series.x(!_)"        Names.Add "_", y        ExecuteExcel4Macro "series.y(,!_)"        Names("_").Delete    End IfEnd WithActiveChart.ChartArea.SelectEnd Sub

An alternative method is to assign names to the arrays (similar to above workaround) and then set the series to refer to the assigned names. This works ok in all versions as long as you save in xls format, but there appears to be a length limitation for named arrays of 8192 characters when saving to the new xlsx/xlsm/xlsb formats.