2015-12-17 160 views
2

我想用Excel VBA默認添加帶百分比的圖表數據標籤。這是我創建圖表的代碼:如何添加包含百分比的圖表數據標籤?

Private Sub CommandButton2_Click() 
ActiveSheet.Shapes.AddChart.Select 
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$A$6:$D$6") 
ActiveChart.ChartType = xlDoughnut 
End Sub 

它只創建沒有信息標籤的甜甜圈圖表。

另外,當我想創建另一個具有相同信息的圖表類型時,我如何更改圖表的座標,使其不會看起來像覆蓋同一個圖表?

回答

1

這裏是有數據標籤以百分比的一種方式:

  Private Sub CommandButton2_Click() 
Dim Cell As Range 
    Set Cell = ActiveCell 
      Set Myrange = Sheets("Sheet1").Range("$A$6:$D$6") 

      ActiveSheet.Shapes.AddChart.Select 
      ActiveChart.SetSourceData Source:=Myrange 
      ActiveChart.ChartType = xlDoughnut 

      With PlotArea 
       ActiveChart.ApplyLayout (6) 
      End With 

      With ActiveChart 
       .Legend.Delete 
       '.ChartTitle.Delete 
       '.ChartTitle.Text = "Here goes your tittle" 
      End With 

     With ActiveChart.SeriesCollection(1) 
      .Points(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
      .Points(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
      .Points(3).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
      .Points(4).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
     End With 

    With ActiveChart.Parent 
      .Height = 200 ' resize 
      .Width = 300 ' resize 
      .Top = Cell.Top ' reposition 
      .Left = Cell.Left ' reposition 
     End With 

      End Sub 

圖的第二式:

Private Sub CommandButton2_Click() 
    Set MyRange = Sheets("Sheet1").Range("$A$6:$D$6") 

    ActiveSheet.Shapes.AddChart.Select 
    ActiveChart.SetSourceData Source:=MyRange 
    ActiveChart.ChartType = xlColumnClustered 

    With PlotArea 
     ActiveChart.ApplyLayout (2) 
    End With 

    With ActiveChart 
     .Legend.Delete 
     '.ChartTitle.Delete 
     '.ChartTitle.Text = "Here goes your tittle" 
    End With 

With ActiveChart.SeriesCollection(1) 
    .Points(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
    .Points(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
    .Points(3).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
    .Points(4).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) 
End With 

With ActiveChart.Parent 
    .Height = 200 ' resize 
    .Width = 300 ' resize 
    .Top = 300 ' reposition 
    .Left = 300 ' reposition 
End With 

End Sub 

在這裏你可以找到顏色代碼: http://dmcritchie.mvps.org/excel/colors.htm

+0

我見在百分數之上1,2,3怎麼我可以刪除?也可以改變默認顏色@manu? –

+0

看到我的編輯,我也把它放在線上 – manu

+0

另請參閱:https://msdn.microsoft.com/EN-US/library/office/dn254146.aspx – Luuklag