2017-03-02 141 views
0

我正在學習如何在Excel 2016中使用VBA for Excel。此刻,我正在通過此網站上的任務進行工作:http://www.homeandlearn.org/vba_charts_and_user_forms.html,其中我想顯示散點圖足球隊的成績之一。這是通過用用戶表單中的組合框選擇團隊來完成的。使用UserForm添加SeriesCollection到圖表(組合框)

代碼的結果(見下文)應該是與一號線和標題的散點圖,像這樣: 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 

回答

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比以前「更聰明」,並解釋了源數據。