I am trying to plot around 200 series\'s onto one chart and am trying to use a for loop to plot all the series\'s for me however, when I run the following code, only the first s
From your code I believe you want to plot data series that are vertical instead of horizontal and have a very misleading variable name - used r for Columns.
First, remove the equal sign for the Range() to work
xAxis = "Compilation!A7:A7507"
originCell = "Compilation!B7:B7507"
Then you are keep adding series to the chart, regardless of how many is in there.
Next issue is that ActiveChart.SeriesCollection(i)
should not relate to i
, as you only want to add if "YES".
Code below should work for you, assuming that cells in Row 7 may equal to "YES". If it is "YES" then the data below it will be added to the chart (should not include itself as you have done). Will also handle if there isn't a Chart in Activesheet. It will remove all old series in the Chart before adding the "YES" ones.
Comment out my TEST DATA row and uncomment ACTUAL DATA:
Sub AddDataToChart1()
Const YesNoRow As Long = 7 ' Yes/No should not be plotted in the chart
Const xAxis As String = "Compilation!A8:A13" ' TEST DATA
'Const xAxis As String = "Compilation!A8:A7507" ' ACTUAL DATA
Dim oRngAxis As Range, oCht As Chart
Dim i As Long ' Offset counter
Dim n As Long ' Number of data series in chart
On Error Resume Next
' Check if existing chart available
Set oCht = ActiveSheet.ChartObjects(1).Chart
If oCht Is Nothing Then Set oCht = ActiveSheet.Shapes.AddChart.Chart
On Error GoTo 0
' Chart Object valid, add series
If Not oCht Is Nothing Then
Set oRngAxis = Range(xAxis)
With oCht
' Remove previous data
For i = .SeriesCollection.Count To 1 Step -1
.SeriesCollection(i).Delete
Next
n = 0
For i = 1 To 200
If UCase(oRngAxis.Worksheet.Cells(YesNoRow, oRngAxis.Column + i).Value) = "YES" Then
n = n + 1
If n > .SeriesCollection.Count Then
.SeriesCollection.NewSeries
End If
.SeriesCollection(n).XValues = oRngAxis
.SeriesCollection(n).Values = oRngAxis.Offset(0, i)
.SeriesCollection(n).Name = "Col " & Split(oRngAxis.Offset(0, i).Address, "$")(1)
End If
Next i
End With
Set oCht = Nothing
Set oRngAxis = Nothing
End If
End Sub
Sample Data and Output:
UPDATE:
Add below code to Compilation sheet to make whenever a cell change in row 7 it will update the Chart immediately! You can also move the sub AddDataToChart1 to there too:
Private Sub Worksheet_Change(ByVal oRng As Range)
If Not Intersect(oRng, Rows(7)) Is Nothing Then AddDataToChart1
End Sub