Looping through cells, building a range in VBA
Question
I am looking to loop through cells and build a range for a graph. My main issue is that I cannot figure out how to incorporate the 'i' into the range. Example:
Dim name As String
Dim newChart as Chart
Dim i as Integer
Set newChart = Charts.add
For i = 1 To 20
accName = Range("C" & i).Value 'I understand why this works.
With newChart
.ChartType = xlColumnClustered
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = accName
.SeriesCollection(1).Values = wb.Worksheets("Summary-Account").Range("E&i:G&i, I&i:K&i, M&i:O&i, Q&i:S&i") 'How can I get this to work?
.SeriesCollection(1).XValues = wb.Worksheets("Summary-Account").Range("E3:G3, I3:K3, M3:O3, Q3:S3")
End With
i = i + 1
Loop
Solution
You probably need to have:
.SeriesCollection(1).Values = wb.Worksheets("Summary-Account").Range("E" & i & ":G" & i & ", I" & i & ":K" & i & ", M" & i & ":O" & i & ", Q" & i & ":S" & i)
Not the clearest line ever, but should give you the pattern to go by. There are other problems like needing a "Next i" instead of a "Loop" and no i=i+1, but on my computer this gave me a graph with multiple series on it.
OTHER TIPS
You don't increment manually
i
.
The functionfor loop
already does it for you.
So remove thati = i + 1
.Now, to make your
Range
work, you would need its "" to be something like this :Range("E" & i & ":G" & i
). I don't quite understand what you are trying to achieve with trying to take data from 6 different columns.. See range for further information.
Try
.SeriesCollection(1).Values = Range("E1").Resize(20,1).Value
this will copy all the values into an array for use in series collection
use Next i
instead of Loop
; and get rid of that i = i+1
.
Also, use "E" & i & ":G" & i
instead of "E&i:G&i"
One step further, in vba
Dim i as double
For i = 1 to 100 Step 10 '<= Step 10 means when updating i, i = i + 10, and default value would be 1
Loop '<=breaks here, compile error is expected.
this is not even valid in syntax, the keyword Loop
is associated with another keyword Do
, and For
is associated with Next