Question

I'm new to VBA. I'm attempting to create over 500 xlClusteredColumn charts using two columns of information and I'd like to expedite the work. The first column contains names I'd like to use for named ranges (i.e.: Line1, Line2, etc.) and the second column contains the indirect references of the data ranges (i.e., Sheet1!C4:D28, Sheet1!C28:D90). I noticed that if I use a named range for the "Chart Data Series" field, the data shows up nicely (but I have to first create that named range being sure to include the INDIRECT formula in the reference, (e.g.: Named Range Line1 is equal to =INDIRECT(Sheet1!C4:C28)). The ranges will be static.

In reviewing prior questions I couldn't seem to find a solution that would select the first cell in this set and name it, then uses the second cell to define that range. I think I might need the ActiveWorkbook.Names.Add Name:= formula and combine it with a loop (but I couldn't get it to use a selection or cell to define the Add Name aspect, only a hard coded name).

If the solution requires it, I can go back and extract the individual ranges (i.e.: C4:D28) from the cell and have the chart reference only that if it makes the code simpler. I know my first outlined attempt isn't the only solution and there's probably one much more elegant. I figured using named ranges would speed up the chart work, but perhaps there's a way to cut that step out?

Populating a new sheet with all the charts for each of these ranges would be icing on the cake, but I'll be happy enough receiving help to get the data set up to chart.

Example information:

NameRange1 (let's say in cells A1:A4)

  • WKD_1_NB
  • WKD_2_EB
  • WKD_3_EB
    SerRange1 (in cells B1:B4)
  • WKDpivot!C4:D43
  • WKDpivot!C84:D140
  • WKDpivot!C197:D233

    (Chart data range requires the reference of named range "WKD_1_NB" to be '=INDIRECT(WKDpivot!C4:D43)' in order for the chart to work.

  • Était-ce utile?

    La solution

    OK so why don't you try the two-step process. I am going to do this without Indirect because I don't see that it is necessary.

    Sub CreateNames()
    Dim rng As Range
    Dim r As Range
    Dim myName As String
    Dim addr As String
    
    Set rng = Range("A1:A2") '## Modify as needed
    For Each r In rng.Cells
        myName = r.Value
        addr = "=" & r.Offset(0, 1).Value
        ThisWorkbook.Names.Add myName, addr
    
    Next
    
    End Sub
    

    This creates your names (screenshot). Note there are some rules about naming conventions and allowable names, etc., the code above does not take any of these in to account.

    enter image description here

    From there it should be fairly simple to create a loop that adds your charts one by one, and assigns each named range to each chart.

    Licencié sous: CC-BY-SA avec attribution
    Non affilié à StackOverflow
    scroll top