我需要绘制一组数据的折线图。我知道包含时间序列的列(C26 到底部),并且我会知道调用它的按钮中的数据列以及数据从 (26) 开始的行。标签将位于第 26 行。按钮将位于第 24 行。数据不包含空格。
图表需要有数据标签。这是我已经取得的进展,任何建议,请告诉我!目前它仅在时间轴上绘制 1。
Sub GraphTest()
Dim xaxis As Range
Dim yaxis As Range
Dim fullRange As Range
Dim topcell As Range
Set xaxis = Range("$B$26", Range("$B$26").End(xlDown))
Set yaxis = ActiveSheet.Buttons(Application.Caller).TopLeftCell
Set yaxis = Range(Cells(yaxis.Row, yaxis.Column).Offset(2, 0), Cells(yaxis.Row, yaxis.Column).Offset(2, 0).End(xlDown))
Set topcell = ActiveSheet.Buttons(Application.Caller).TopLeftCell
Set fullRange = Union(xaxis, yaxis)
fullRange.Select
topcell.Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=fullRange
End Sub()
最佳答案
如果您单独创建和控制系列,而不是使用 SetSourceData
一次将整个数据集插入其中,事情就会变得容易得多。示例:
Dim xaxis As Range
Dim yaxis As Range
Set xaxis = Range("$B$26", Range("$B$26").End(xlDown))
Set yaxis = Range("$C$26", Range("$C$26").End(xlDown))
Dim c As Chart
Set c = ActiveWorkbook.Charts.Add
Set c = c.Location(Where:=xlLocationAsObject, Name:="Sheet1")
With c
.ChartType = xlLine
' set other chart properties
End With
Dim s As Series
Set s = c.SeriesCollection.NewSeries
With s
.Values = yaxis
.XValues = xaxis
' set other series properties
End With
编辑
所谓的“折线图”并不总是按照您的预期运行。这就是一个典型的例子。当时间位于 x 轴上且格式为 dd/mm/yyyy hh:mm 时,折线图会强制共享相同日期(日)的所有点放入同一个 bin 中,无论一天中的时间如何。他们为什么要这样做?我没有任何线索。折线图可以做各种其他疯狂的事情。
我很确定你想要的是散点图。事实上,您想要的几乎总是散点图,而不是折线图。
这是一个例子。我制作了自己的温度数据,但保留了您的日期时间。
使用此代码生成:
Dim xaxis As Range
Dim yaxis As Range
Set xaxis = Range("$B$26", Range("$B$26").End(xlDown))
Set yaxis = Range("$C$26", Range("$C$26").End(xlDown))
Dim c As Chart
Set c = ActiveWorkbook.Charts.Add
Set c = c.Location(Where:=xlLocationAsObject, Name:="Sheet1")
With c
.ChartType = xlXYScatterLines 'A scatter plot, not a line chart!
' set other chart properties
End With
Dim s As Series
Set s = c.SeriesCollection.NewSeries
With s
.Values = yaxis
.XValues = xaxis
' set other series properties
End With
With c.Axes(xlCategory)
.MajorUnit = 0.125
End With
With c
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Time"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Temperature"
.HasLegend = False
End With
关于Excel 2010 VBA 绘制图表宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8477581/