VBA图表范围减去

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VBA图表范围减去相关的知识,希望对你有一定的参考价值。

我找到了这个代码,每次运行时都会向图表添加一个额外的列。意思是第一次运行它显示第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

我想要执行与此代码相反的操作,因此不应添加列,而应减去一列。如何修改代码来执行此操作?

(链接:VBA: Modify chart data range

谢谢!

答案

尝试更改线路

Set oRng = oRng.Worksheet.Range(oRng, oRng.Offset(0, 1))

Set oRng = oRng.Worksheet.Range(oRng.Offset(0, 1), oRng.Offset(0, 1))

以上是关于VBA图表范围减去的主要内容,如果未能解决你的问题,请参考以下文章

Excel VBA 更新图表系列

将控件(ActiveX或非ActiveX)添加到图表(Excel VBA)

VBA代码:减去值直到它达到零

VBA循环使用另一张表中的数据更新图表中的系列

VBA绘制Excel图表

将图表从单元格范围更改为命名范围