2016-08-14 94 views
0

這裏建立時爲圖表是我寫每一個按鈕被按下的時間來重新生成的圖表的代碼:使用VBA

Sub MakeChart() 
    ActiveWorkbook.Charts("cht_hgn_hgn").Delete 
    Dim s As Series 
    Dim sh As Worksheet 
    Dim cs As Chart 
    Set sh = Worksheets("clc_hgn_hgn") 
    Set cs = ActiveWorkbook.Charts.Add 
    cs.Name = "cht_hgn_hgn" 
    cs.ChartType = xlLine 
    For iCount = 3 To 3 
     Debug.Print (iCount) 
     Set s = cs.SeriesCollection.NewSeries 
     s.Name = sh.Cells(1, iCount).Value 
     s.values = sh.Range(sh.Cells(3, iCount), sh.Cells(41, iCount)) 
     s.XValues = sh.Range(sh.Cells(3, 1), sh.Cells(41, 1)) 
    Next iCount 
End Sub 

這裏是源數據的屏幕截圖:

http://imgur.com/a/wEEiT

這裏是圖表的屏幕截圖:

http://imgur.com/a/BDa5s

問題在於圖例中的標籤(至少)和沿着x軸看起來確實搞砸了。我在代碼中做了什麼錯誤?

謝謝!

+1

如果可以手動修改圖表,然後錄製宏並檢查生成的代碼。問題在於源範圍中的空單元格。 – Slai

回答

1

數據主要有兩個問題,並從中創建圖表。

首先:您需要設置空白單元格繪製在圖表上的方式。可以使用Chart.DisplayBlanksAs Property

第二:雖然ActiveWorkbook.Charts.Add「默認」系列從活動工作表的數據中添加。因此你可能不需要的那些系列應該被刪除。

所以可能:

Sub MakeChart() 
    On Error Resume Next 
    ActiveWorkbook.Charts("cht_hgn_hgn").Delete 
    On Error GoTo 0 

    Dim s As Series 
    Dim sh As Worksheet 
    Dim cs As Chart 
    Dim lLastRow As Long, lColumnCount As Long, lLastColumn As Long 

    Set sh = Worksheets("clc_hgn_hgn") 
    lLastRow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row 
    lLastColumn = 5 

    Set cs = ActiveWorkbook.Charts.Add 
    cs.Name = "cht_hgn_hgn" 
    cs.ChartType = xlLine 

    'set the way that blank cells are plotted on the chart 
    cs.DisplayBlanksAs = xlInterpolated 
    'delete the series which are created while ActiveWorkbook.Charts.Add 
    'since we want creating our own series now 
    For Each s In cs.SeriesCollection 
    s.Delete 
    Next 

    For lColumnCount = 3 To lLastColumn 
     Debug.Print (lColumnCount) 
     Set s = cs.SeriesCollection.NewSeries 
     s.Name = sh.Cells(1, lColumnCount).Value 
     s.Values = sh.Range(sh.Cells(3, lColumnCount), sh.Cells(lLastRow, lColumnCount)) 
     s.XValues = sh.Range(sh.Cells(3, 1), sh.Cells(lLastRow, 1)) 
    Next lColumnCount 

End Sub 
+0

很好的答案。但是我沒有使用xlInterpolated。如果零值是一個問題,那麼也許我使用了錯誤的圖表類型。 – posfan12