使用VBA构建时错误的图表

时间:2016-08-14 01:25:17

标签: excel vba excel-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 个答案:

答案 0 :(得分: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