Reputation: 437
I have what I hope is a relatively simple request.
I am working on a macro which will automatically format a large number of charts that I am creating. I have got a problem, however, in that the number of series that each chart contains varies a lot.
If I try to run my current code on a chart that only has four series, for example, it errors when it reaches the code below and cannot process the code thereafter, as it is expecting a fifth series to format. I believe I need to implement code that says - "IF the chart has a fifth series THEN apply this next line of the macro".
The code below is that which I am using to format each series. How should this be encased within an if statement as described above?
ActiveChart.LegEND.Select
ActiveChart.LegEND.LegendEntries(5).Select
ActiveChart.SeriesCollection(5).Select
With Selection.Format.Line
.Visible = msoTrue
.Weight = 1.5
End With
Upvotes: 0
Views: 1423
Reputation: 3506
You can use the Count
member of the SeriesCollection
collection (documentation), this returns the number of series in the chart. You could use something like:
ActiveChart.LegEND.Select
If ActiveChart.SeriesCollection.Count = 5 Then
ActiveChart.LegEND.LegendEntries(5).Select
ActiveChart.SeriesCollection(5).Select
With Selection.Format.Line
.Visible = msoTrue
.Weight = 1.5
End With
End If
This will only work if you have exactly 5 series, if you have more then the Count
evaluates to say, 6, the above formatting would not be applied.
You can change the If statement slightly to the following:
If ActiveChart.SeriesCollection.Count >= 5 Then
ActiveChart.LegEND.LegendEntries(5).Select
ActiveChart.SeriesCollection(5).Select
With Selection.Format.Line
.Visible = msoTrue
.Weight = 1.5
End With
End If
You can then repeat this block in your code for >= 6 and it should work. On a side note, this is probably not the most efficient way to code this as you are repeating blocks of code, but that's not really the point of this question.
Upvotes: 2