VBA: Modify chart data range

后端 未结 4 1209
梦毁少年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:37

    Assuming that you only run the macro with a Chart Selected, my idea is to alter the range in the formula for each Series. You can of cause change to apply to all Charts in a Worksheet.

    UPDATE: Have changed code to accommodate multiple series with screenshots

    Formatting of new series string needs to include apostrophes around the worksheet name (already changed below): aFormulaNew(i) = "'" & oRng.Worksheet.Name & "'" & "!" & oRng.Address. Also, if looking to change rows rather than columns, change the offset to Set oRng = oRng.Worksheet.Range(oRng, oRng.Offset(1, 0)) or as needed. Can also include oRng.Offset(1, 0) for the first element in the range to adjust the start position of the series: Set oRng = oRng.Worksheet.Range(oRng.Offset(1, 0), oRng.Offset(1, 0))

    Sub ChartRangeAdd()
        On Error Resume Next
        Dim oCht As Chart, aFormulaOld As Variant, aFormulaNew As Variant
        Dim i As Long, s As Long
        Dim oRng As Range, sTmp As String, sBase As String
        
        Set oCht = ActiveSheet.ChartObjects(1).Chart
        oCht.Select
        For s = 1 To oCht.SeriesCollection.count
            sTmp = oCht.SeriesCollection(s).Formula
            sBase = Split(sTmp, "(")(0) & "()" ' "=SERIES(" & ")"
            sTmp = Split(sTmp, "(")(1) ' "..., ..., ...)"
            aFormulaOld = Split(Left(sTmp, Len(sTmp) - 1), ",") ' "..., ..., ..."
            aFormulaNew = Array()
            ReDim aFormulaNew(UBound(aFormulaOld))
            ' Process all series in the formula
            For i = 0 To UBound(aFormulaOld)
                Set oRng = Range(aFormulaOld(i))
                ' Attempt to put the value into Range, keep the same if it's not valid Range
                If Err.Number = 0 Then
                    Set oRng = oRng.Worksheet.Range(oRng, oRng.Offset(0, 1))
                    aFormulaNew(i) = "'" & oRng.Worksheet.Name & "'" & "!" & oRng.Address
                Else
                    aFormulaNew(i) = aFormulaOld(i)
                    Err.Clear
                End If
            Next i
            sTmp = Replace(sBase, "", Join(aFormulaNew, ","))
            Debug.Print "Series(" & s & ") from """ & oCht.SeriesCollection(s).Formula & """ to """ & sTmp & """"
            oCht.SeriesCollection(s).Formula = sTmp
            sTmp = ""
        Next s
        Set oCht = Nothing
    End Sub
    

    Sample data - Initial

    InitialData

    After first run:

    FirstRun

    Second Run:

    SecondRun

    Third Run:

    ThirdRun

提交回复
热议问题