VBA: Modify chart data range

后端 未结 4 1223
梦毁少年i
梦毁少年i 2020-11-30 11:54

My \"Chart data range\" is =\'sheet1\'!$A$1:$Z$10. I\'d like to make a VBA macro (or if anybody knows a formula I can use, but I couldn\'t figure one out) to in

4条回答
  •  误落风尘
    2020-11-30 12:23

    Assuming that you want to expand the range (by adding one extra column) to add one more observation for each series in you diagram (and not to add a new series), you could use this code:

    Sub ChangeChartRange()
        Dim i As Integer, r As Integer, n As Integer, p1 As Integer, p2 As Integer, p3 As Integer
        Dim rng As Range
        Dim ax As Range
    
        'Cycles through each series
        For n = 1 To ActiveChart.SeriesCollection.Count Step 1
            r = 0
    
            'Finds the current range of the series and the axis
            For i = 1 To Len(ActiveChart.SeriesCollection(n).Formula) Step 1
                If Mid(ActiveChart.SeriesCollection(n).Formula, i, 1) = "," Then
                    r = r + 1
                    If r = 1 Then p1 = i + 1
                    If r = 2 Then p2 = i
                    If r = 3 Then p3 = i
                End If
            Next i
    
    
            'Defines new range
            Set rng = Range(Mid(ActiveChart.SeriesCollection(n).Formula, p2 + 1, p3 - p2 - 1))
            Set rng = Range(rng, rng.Offset(0, 1))
    
            'Sets new range for each series
            ActiveChart.SeriesCollection(n).Values = rng
    
            'Updates axis
            Set ax = Range(Mid(ActiveChart.SeriesCollection(n).Formula, p1, p2 - p1))
            Set ax = Range(ax, ax.Offset(0, 1))
            ActiveChart.SeriesCollection(n).XValues = ax
    
        Next n
    End Sub
    

提交回复
热议问题