使用 VBA Excel 创建散点图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31778834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using VBA Excel to create Scatter Plot
提问by lucasvinhtran
This is my VBA code to create a scatter plot in Excel:
这是我在 Excel 中创建散点图的 VBA 代码:
Sub createmychart()
Dim Chart1 As Chart
Set Chart1 = Charts.Add
With Chart1
.SetSourceData Source:=Sheets("usd_download data").Range("A2:B26001")
.ChartType = xlXYScatter
End With
End Sub
However, it ended up like this:
然而,结果是这样的:
But I would like to have a graph like this:
但我想要一个这样的图表:
I tried a lots but cannot figure out how to do this.
我尝试了很多,但无法弄清楚如何做到这一点。
回答by cronos2546
Without knowing what your data looks like, your code appears to have two series of data while you want just one.
在不知道您的数据是什么样子的情况下,您的代码似乎有两个系列的数据,而您只需要一个。
Sub createmychart()
Dim Chart1 As Chart
Set Chart1 = Charts.Add
With Chart1
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
'Change to what your series should be called
.SeriesCollection(1).Name = "=""Values"""
.SeriesCollection(1).XValues = "=usd_download data!$A:$A001"
.SeriesCollection(1).Values = "=usd_download data!$B:$B001"
End With
End Sub
回答by Michael Ling
I was struggling with the chartobject, chart and SeriesCollection as well. NewSeries is the method to add one Series in the SeriesCollection collection, and since it's only one series, so you can use SeriesCollection(1) to refer to it.
我也在为图表对象、图表和 SeriesCollection 苦苦挣扎。NewSeries 是在SeriesCollection 集合中添加一个Series 的方法,由于它只是一个系列,所以可以使用SeriesCollection(1) 来引用它。
回答by sabrinahewa
This worked for me (sorry different cell ranges but u get the idea)
这对我有用(对不起,不同的单元格范围,但你明白了)
Private Sub CommandButton1_Click()
Dim xrng As Range
Dim yrng As Range
Set xrng = Range("A12:A17")
Set yrng = Range("B12:B17")
Dim Chart1 As Chart
Set Chart1 = Charts.Add
With Chart1
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
'Change to what your series should be called
.SeriesCollection(1).Name = "=""Values"""
.SeriesCollection(1).XValues = xrng
.SeriesCollection(1).Values = yrng
End With
End Sub


