我想调整x和y轴,以使用来自放置图表的同一工作表的特定范围内的值。 而且,每列都是不同的颜色(图表上有图例) 到目前为止,这是我的代码:
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 :(得分: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
您只需要调整数据选择和名称,这应该是一个好的开始