2015-04-07 118 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