使用UserForm(组合框)将SeriesCollection添加到图表

时间:2017-03-02 11:03:36

标签: excel vba charts userform excel-2016

我正在学习在Excel 2016中使用VBA for excel。目前我在这个网站上完成了一项任务:http://www.homeandlearn.org/vba_charts_and_user_forms.html我要在其中展示一个足球队的分散情节&# 39;结果。这是通过在用户表单中选择具有组合框的团队来完成的。

代码的结果(见下文)应该是一个带有一行和一个标题的散点图,如下所示: http://www.homeandlearn.org/images/vba_charts/chart_arsenal.gif(由于某种原因无法上传)

但是,这是我的代码的结果。

enter image description here

如何使用与网站完全相同的代码,图表无法显示所选数据和标题?我也想知道第五个系列的来源来自,因为我只有四列。

代码如下(并且对于网站上描述的代码是唯一的):

Private Sub cmdLoad_Click()
    If cbSelect.Text = "Select a chart" Then
        MsgBox "Please select a chart"
        Exit Sub
    End If

    Dim MyChart As Chart
    Dim ChartData As Range
    Dim ChartIndex As Integer
    Dim ChartName As String

    ChartIndex = cbSelect.ListIndex

    Select Case ChartIndex
        Case 0
            Set ChartData = ActiveSheet.Range("B2:B20")
            ChartName = ActiveSheet.Range("B1").Value
        Case 1
            Set ChartData = ActiveSheet.Range("C2:C20")
            ChartName = ActiveSheet.Range("C1").Value
        Case 2
            Set ChartData = ActiveSheet.Range("D2:D20")
            ChartName = ActiveSheet.Range("D1").Value
        Case 3
            Set ChartData = ActiveSheet.Range("E2:E20")
            ChartName = ActiveSheet.Range("E1").Value
    End Select

    Application.ScreenUpdating = False

    Set MyChart = ActiveSheet.Shapes.AddChart(xlXYScatterLines).Chart

    MyChart.SeriesCollection.NewSeries
    MyChart.SeriesCollection(1).Name = ChartName
    MyChart.SeriesCollection(1).Values = ChartData
    MyChart.SeriesCollection(1).XValues = ActiveSheet.Range("A2:A20")

    'Save chart as an image, remove the chart, then set updating screen to ON'
    Dim imageName As String
    imageName = ThisWorkbook.Path & "\gs16_pictures" & Application.PathSeparator & "TempChart.gif"
    MyChart.Export Filename:=imageName, FilterName:="GIF"
    ActiveSheet.ChartObjects(1).Delete
    Application.ScreenUpdating = True
    'Load picture in user form
    UserForm1.Image1.Picture = LoadPicture(imageName)

cbSelect初始化如下

Private Sub UserForm_Initialize()
    cbSelect.AddItem Range("B1") 'Arsenal
    cbSelect.AddItem Range("C1") 'Man City
    cbSelect.AddItem Range("D1") 'Newcastle
    cbSelect.AddItem Range("E1") 'Cardiff
    cbSelect.TextAlign = fmTextAlignCenter
End Sub

1 个答案:

答案 0 :(得分:0)

问题出在声明中

Set MyChart = ActiveSheet.Shapes.AddChart(xlXYScatterLines).Chart

此语句自动绘制整个数据表。为了防止它,有必要明确声明SourceData。以下是您需要的代码,而不是以MyChart.SeriesCollection

开头的行
With MyChart
    .SetSourceData Source:=ChartData
    .HasTitle = True
    .ChartTitle.Text = ChartName
    .SeriesCollection(1).XValues = ActiveSheet.Range("A2:A20")

End With

我不确定为什么Excel 2016与网站上的示例存在差异。也许Excel更聪明"比以前解释了源数据。