質問

I'm still a vba novice so I apologize in advance for a simple problem.

I have about 500 charts with two series each (one is a clustered column and the other is a line). For each chart, I'd like to rename both series and loop through all charts on the sheet. Below is the code that I started to piece together so far.

    Sub RenameSeries()
    Dim i As Integer

    'Loops through charts
    For i = 1 To ActiveSheet.ChartObjects.Count
        With ChartObject.Chart.SeriesCollection
            .Name(1) = "Name1"
            .Name(2) = "Name2"
    End With
    Next i

    End Sub

I'm running into trouble with the With ChartObject line. I'm not sure how to iteratively select each chart, make those two changes, and move on to the next chart. Thank you in advance for reading and providing your suggestions.

役に立ちましたか?

解決

It is the SeriesCollection that needs to be indexed, not Name. (Each collection only has one Name).

I've tested this, but it is essentially the same as Tim's:

Sub RenameSeries()
    Dim ws As Worksheet
    Dim i As Integer

    Set ws = ActiveSheet
    'Loops through charts
    For i = 1 To ws.ChartObjects.Count
        With ws.ChartObjects(i).Chart
            .SeriesCollection(1).Name = "Name1"
            .SeriesCollection(2).Name = "Name2"
        End With
    Next i

End Sub

If one or more of the charts doesn't have 2 SeriesCollections, and you are happy to ignore (skip) this inconsistency, then you can use:

Sub RenameSeries()
    Dim ws As Worksheet
    Dim i As Integer

    Set ws = ActiveSheet
    'Loops through charts
    For i = 1 To ws.ChartObjects.Count
        With ws.ChartObjects(i).Chart
            .SeriesCollection(1).Name = "Name1"
            If .SeriesCollection.Count > 1 Then
                .SeriesCollection(2).Name = "Name2"
            End If
        End With
    Next i

End Sub

It is better, of course, to debug the code to discover why you have this unexpected inconsistency - perhaps a rogue chart that is hiding behind another one.


A side-note, 500 charts is a lot. I would prefer to use, perhaps, comboboxes to dynamically change the data-source(s) for fewer charts. I appreciate, however, that this requires quite a bit of Excel knowledge.

他のヒント

Untested:

Sub RenameSeries()
Dim i As Integer

    'Loops through charts
    For i = 1 To ActiveSheet.ChartObjects.Count
        With ActiveSheet.ChartObjects(i).Chart.SeriesCollection
            .item(1).Name = "Name1"
            .item(2).Name = "Name2"
        End With
    Next i
End Sub
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top