2017-05-05 59 views
0

我试图创建一个数据透视表。但有几个系列是负面的。所以我想将它们转换到负轴,并试图使主轴和副轴的水平相同。辅助轴和主轴是使用VBA的同一级别

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

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

回答

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