使用VBA构build时出现错误的图表

这里是我写的每次按下button时重新生成图表的代码:

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

问题是,图例中的标签(至less)和x轴看起来真的搞砸了。 我在代码中做了什么错误?

谢谢!!

您的数据主要有两个问题,并从中创build图表。

首先:您需要设置空白单元格绘制在图表上的方式。 对于此Chart.DisplayBlanksAs属性可以使用。

第二: 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