2015-04-07 148 views
0

我想調整x和y軸以使用放置圖表的同一工作表中特定範圍內的值。 並且還,每一列代表不同的顏色(與目前在圖表上的圖例) 這是到目前爲止我的代碼:在Excel中使用vba編輯圖表

Dim cht As ChartObject 
    Set chtChart = Worksheets("Sheet1").ChartObjects.Add(Left:=75, Width:=300, Top:=75, Height:=300).Chart 
    With chtChart 
    .ChartType = xlColumnStacked 
    End With 

編輯:我很好,只要使用的圖表,它沒有成爲ChartObject。但是,當我使用「圖表」時,另一張圖紙被創建(除了將圖表放在所需的圖紙上),我想避免這種情況。

回答

0

下面是一些代碼,可以幫助你:

Sub Graph() 

Dim Gr As Chart 

     Set Gr = ActiveWorkbook.Worksheets("Sheet1").ChartObjects.Add(Left:=75, Width:=300, Top:=75, Height:=300).Chart 
      With Gr 
      'Définition des données sources du graphique 
      .SetSourceData Source:=Range(Sheets(Src_Name).Cells(2, 1), Sheets(Src_Name).Cells(20, 5)), PlotBy:=xlRows 
      'Type de graphique 
      .ChartType = xlColumnStacked 
      'Place 
      .Location Where:=xlLocationAsNewSheet, Name:=NewSheetName 
      'Titre 
      .HasTitle = True 
      .ChartTitle.Characters.Text = "Chart Title" 
      'Data Series 1 
      .SeriesCollection.NewSeries 
      .SeriesCollection(1).Values = Range(Sheets(Src_Name).Cells(2, 2), Sheets(Src_Name).Cells(20, 5)) 
      .SeriesCollection(1).XValues = Range(Sheets(Src_Name).Cells(2, 1), Sheets(Src_Name).Cells(20, 1)) 
      .SeriesCollection(1).AxisGroup = 1 
      .SeriesCollection(1).Name = "MTTF" 
      'Data Series 2 
      .SeriesCollection.NewSeries 
      .SeriesCollection(2).Values = Range(Sheets(Src_Name).Cells(2, 2), Sheets(Src_Name).Cells(20, 5)) 
      .SeriesCollection(2).XValues = Range(Sheets(Src_Name).Cells(2, 1), Sheets(Src_Name).Cells(20, 1)) 
      .SeriesCollection(2).Name = "MTTR" 
      'Second axis 
      .SeriesCollection(2).AxisGroup = 2 
      '.SeriesCollection(3).Delete 
      '.SeriesCollection(i).Format.Line.Weight = 1 
      '.SeriesCollection(i).Format.Line.ForeColor.RGB = RGB(int1 as integer, int1 as integer, int3 as integer) ' pour une ligne 
      '.SeriesCollection(i).Format.Fill.ForeColor.RGB = RGB(int1 as integer, int1 as integer, int3 as integer) ' pour une area 

      'Axis parameters 
      .Axes(xlCategory, xlPrimary).HasTitle = True 
      .Axes(xlCategory, xlPrimary).AxisTitle.Text = "Age" 
      .Axes(xlValue, xlPrimary).HasTitle = True 
      .Axes(xlValue, xlPrimary).AxisTitle.Text = "Hours" 
      .PlotArea.Interior.ColorIndex = 2 
      .Axes(xlValue).MajorGridlines.Border.LineStyle = xlDot 
      .ChartArea.Font.Size = 14 
      .Deselect 
      End With 

      'Legend positioning 
      With ActiveChart.Legend 
       .Left = 350 
       .Top = 75 
      End With 
      'Drawing area positiong 
      With ActiveChart.PlotArea 
       .Width = 550 
       .Height = 350 
      End With 



'Clean memory 
Set Gr = Nothing 



End Sub 

你只需要調整您的數據選擇和名稱,它應該是一個良好的開端

+0

如果它夠你PLZ驗證答案關閉主題 – R3uK