使用VBA,辅助轴和主轴具有相同的级别

时间:2017-05-05 13:48:01

标签: vba pivot-table axis

我正在尝试创建数据透视表。但有几个系列是负面的。所以我想将它们转移到负轴并尝试使主轴和副轴的水平相同。

我正在使用以下代码。但这并没有帮助我正确地格式化轴。

Sub createChart()

On Error Resume Next

ActiveChart.Delete
Application.ScreenUpdating = False

Dim myPT As PivotTable

Dim primaryMax As Integer
Dim primaryMin As Integer
Dim secondaryMax As Integer
Dim secondaryMin As Integer
Dim max As Integer
Dim min As Integer

Set myPT = ActiveSheet.PivotTables("CPivotTable")
Set mySheet = Sheets("PivotTable")
myPT.PivotSelect ("")

Charts.Add

ActiveChart.Location Where:=xlLocationAsObject, _
Name:=myPT.Parent.Name
ActiveChart.Parent.Left = Range("D8").Left
ActiveChart.Parent.Top = Range("D8").Top

ActiveChart.ChartType = xlArea



Set ch = ActiveSheet.ChartObjects(1).Chart
For Each ser In ch.SeriesCollection
    If ser.Name Like "Var2" Or ser.Name Like "Var3" Then
        ser.AxisGroup = xlSecondary
    End If
 Next

 With mySheet
        With .ChartObjects(1).Chart.Axes(xlValue)
            primaryMin = .MinimumScale
            primaryMax = .MaximumScale
        End With
        With .ChartObjects(1).Chart.Axes(xlValue, xlSecondary)
            secondaryMin = .MinimumScale
            secondaryMax = .MaximumScale
        End With

        If primaryMax > secondaryMax Then
            max = primaryMax
        Else
            max = secondaryMax
        End If

        If primaryMin < secondaryMin Then
            min = primaryMin
        Else
            min = secondaryMin
        End If
        With .ChartObjects(1).Chart.Axes(xlValue)
            primaryMin = min
            primaryMax = max
        End With
        With .ChartObjects(1).Chart.Axes(xlValue, xlSecondary)
            secondaryMin = min
            secondaryMax = max
        End With

    End With



Range("A1").Select
Application.ScreenUpdating = True



End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

我使用以下代码来解决我的问题。把它放在这里,以防其他人有同样的问题。

Dim PriMax, PriMin
Dim SecMax, SecMin

ActiveSheet.ChartObjects(1).Activate
ActiveChart.Axes(xlValue, xlPrimary).Select

PriMax = ActiveChart.Axes(xlValue, xlPrimary).MaximumScale
PriMin = ActiveChart.Axes(xlValue, xlPrimary).MinimumScale
SecMin = ActiveChart.Axes(xlValue, xlSecondary).MinimumScale
SecMax = ActiveChart.Axes(xlValue, xlSecondary).MaximumScale

PriMin = SecMin
SecMax = PriMax

ActiveChart.Axes(xlValue, xlPrimary).MaximumScale = PriMax
ActiveChart.Axes(xlValue, xlPrimary).MinimumScale = PriMin
ActiveChart.Axes(xlValue, xlSecondary).MaximumScale = SecMax
ActiveChart.Axes(xlValue, xlSecondary).MinimumScale = SecMin