我正在创建一个生成图表的宏。
图表创建按我预期工作,没有问题。我唯一的问题是 X 轴上显示的日期不正确。
Sub generateChart()
' Select a range starting in row 2.
' This macro will use that range, and create a chart just for them.
Dim rng As Range
Dim randR As Long, randG As Long, randB As Long
Set rng = Selection
Dim numCharts As Long
numCharts = ActiveSheet.ChartObjects.Count
Dim newChart As ChartObject
Dim num As Long
num = rng.Columns.Count
Dim i As Long
For i = 1 To num
randR = Application.WorksheetFunction.RandBetween(1, 200)
randG = Application.WorksheetFunction.RandBetween(0, 255)
randB = Application.WorksheetFunction.RandBetween(0, 255)
With ActiveSheet
Set newChart = ActiveSheet.ChartObjects.Add(Left:=100, Width:=400, Top:=75, Height:=225)
With newChart.Chart
.ChartType = xlXYScatterLines
Debug.Print rng.Address
.SetSourceData Source:=rng
With .FullSeriesCollection(1)
.Name = Cells(1, rng.Columns(i).Column).Value
.Values = Range(Cells(2, rng.Columns(i).Column), _
Cells(rng.Rows.Count + 1, rng.Columns(i).Column))
.XValues = "=Sheet2!$J$2:$J$10"
.Format.Fill.ForeColor.RGB = RGB(randR, randG, randB)
.Format.Line.Visible = msoFalse
.MarkerStyle = 1
.MarkerSize = 8
End With
.SeriesCollection.NewSeries
With .FullSeriesCollection(2)
.Name = "=Sheet2!$Q$1"
.Values = "=Sheet2!$Q$2:$Q$10"
.XValues = "=Sheet2!$J$2:$J$10"
.Format.Line.Visible = msoTrue
.MarkerStyle = 0
End With
.SetElement (msoElementLegendBottom)
' Add titles
Dim titleStr As String
.SetElement (msoElementChartTitleAboveChart)
titleStr = Cells(1, rng.Columns(i).Column).Value & " Time Delay"
With .ChartTitle
.Text = titleStr
.Format.TextFrame2.TextRange.Characters.Text = Cells(1, rng.Columns(i).Column).Value & " Time Delay"
.Format.TextFrame2.TextRange.ParagraphFormat.TextDirection = msoTextDirectionLeftToRight
.Format.TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenter
End With
' Now, hide the points that are 0 value
hideZeroValues newChart
' I thought this would work, but it doesn't seem to do anything
.Axes(xlCategory).CategoryType = xlCategoryScale
End With 'newchart.chart
End With ' ActiveSheet
Next i
End Sub
(注意平均值是正确的,有隐藏的列)
然而!如果我使用“内置”图表创建图表,只需选择数据,我就可以选择格式化为文本。
我在宏中忽略了什么?为什么我似乎无法正确设置 X 值?选择“数字”,然后格式化为日期类别会保留不正确的日期。最后,如果我右键单击图表并尝试选择日期,也许它暗示出了什么问题,“水平轴”是灰色的。
感谢您的任何想法/想法!