2017-05-05 22 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