使用VBA更改图表范围

时间:2018-06-29 13:40:15

标签: excel excel-vba dynamic charts range vba

我希望每次运行代码时都将图表范围向右移一列。因此,最小范围向右移动一个,最大范围向右移动,这意味着计数相同。

示例: 我在单元格P13-U13中有一个过去6周的销售图表,我只想查看6周的数据,因此,当我添加新的第7周时,图表应在单元格Q13-V13中显示数据。 (总共6周)

我找到了这段代码,每次运行时都会在图表中添加一个额外的列。 意思是它第一次运行它显示第1-7周,第二时间1-8,下一个1-9,我希望它显示2-7、3-8、4-9等。 我的想法是更改代码,以便左侧也向右移动一个。但是我还无法使它工作。

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) & "(<FORMULA>)" ' "=SERIES(" & "<FORMULA>)"
    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, "<FORMULA>", 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

(LINK:VBA: Modify chart data range

谢谢!

0 个答案:

没有答案