使用VBA Excel创建Scatter Plot

时间:2015-08-03 03:01:38

标签: excel vba excel-vba

这是我在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

然而,最终结果如下:

enter image description here

但我希望有一个这样的图表:

enter image description here

我尝试了很多,但无法弄清楚如何做到这一点。

3 个答案:

答案 0 :(得分:5)

在不知道您的数据是什么样的情况下,您的代码似乎只有两个系列数据。

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$2:$A$26001"
        .SeriesCollection(1).Values = "=usd_download data!$B$2:$B$26001"
    End With
End Sub

答案 1 :(得分:0)

我也在使用chartobject,chart和SeriesCollection。 NewSeries是在SeriesCollection集合中添加一个Series的方法,因为它只是一个系列,所以您可以使用SeriesCollection(1)来引用它。

答案 2 :(得分:0)

这对我有用(抱歉,不同的单元格范围,但是您知道了)

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