我有一个特殊的问题,随机而来。我正在使用VBA创建一个图表。我首先在XY图表上添加10个数据系列,然后再添加一个数据系列作为聚簇列。代码按原样运行,并创建图表并且所有数据都在那里。
当我尝试更新图表以绘制不同的数据集时,会出现问题。它通常会正常工作一次或两次,但数据将停止显示在图表上,但标签和图例仍将存在。数据仍然存在于图表中,我可以通过转到Excel Select Data菜单并选择其中一个数据系列或重新启动程序再次显示数据,但在我执行其中一个操作之前,它只是一个空图表。
我用来更新情节的代码如下。它只是检查几个单元格以查看实际绘制的数据,然后抓取该数据并将其添加到图表中。我已经逐行逐步完成了,但从来没有遇到过这种问题。
Dim wb As Workbook
Dim ws As Worksheet
Dim cht As ChartObject
Dim rn, rn2, colorRn As Range
Dim i, j, MyLength, numlines, MyEnd As Integer
Dim MyAdd, MyChar As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Data")
Set cht = ws.ChartObjects("Data_Chart")
Application.ScreenUpdating = False
'Find Last row to use in plots, this is due to combo plot limitation
Set rn = ws.Range("D45:M45")
Set rn2 = ws.Range("D43:M43")
MyEnd = CInt(Right(ws.Range("B44").CurrentRegion.Address, 3))
'Clear Prev Plot Series
cht.Activate
numlines = ActiveChart.SeriesCollection.Count
If ActiveChart.SeriesCollection.Count > 0 Then
i = ActiveChart.SeriesCollection.Count
While i > 0
ActiveChart.SeriesCollection(i).Delete
i = i - 1
Wend
Else
End If
'Plot or not range
Set rn = ws.Range("B5:G14")
'Add data series
For i = 1 To rn.Rows.Count
If rn(i, 4) = "Yes" Then
ActiveChart.SeriesCollection.NewSeries
numlines = ActiveChart.SeriesCollection.Count
With ActiveChart.SeriesCollection(numlines)
.Name = ws.Range("B" & CStr(i + 4))
.XValues = ws.Range("B45:B" & MyEnd)
.Values = ws.Range(rn(i, 6) & "45:" & rn(i, 6) & MyEnd)
'format color
.MarkerForegroundColor = rn(i, 5).Cells.Interior.Color
.MarkerBackgroundColor = rn(i, 5).Cells.Interior.Color
.MarkerSize = 3
End With
Else
End If
Next i
'********* Try to insert columns
ActiveChart.SeriesCollection.NewSeries
numlines = ActiveChart.SeriesCollection.Count
With ActiveChart.SeriesCollection(numlines)
.Name = ws.Range("C44")
.XValues = ws.Range("B45:B" & MyEnd)
.Values = ws.Range("A45:A" & MyEnd)
.ChartType = xlColumnClustered
'Format column color
.Format.Fill.ForeColor.RGB = RGB(255, 255, 0)
.Format.Line.ForeColor.RGB = RGB(255, 255, 0)
End With
ActiveChart.ChartGroups(1).GapWidth = 0
'Fix scale for combo plot
ActiveChart.Axes(xlCategory).TickLabelSpacing = 10
ActiveChart.Axes(xlCategory).MajorTickMark = xlOutside
ActiveChart.SetElement (msoElementPrimaryCategoryGridLinesNone)
Call MyRescalePos
Set rn = Nothing
Set cht = Nothing
Set ws = Nothing
Set wb = Nothing
Application.ScreenUpdating = True
Rescale sub
Sub MyRescalePos()
Worksheets("Data").Activate
ActiveSheet.ChartObjects("Data_Chart").Activate
ActiveChart.Axes(xlValue).MinimumScale = Worksheets("Data").Range("Q8")
ActiveChart.Axes(xlValue).MaximumScale = Worksheets("Data").Range("Q9")
ActiveChart.Axes(xlValue).MajorUnit = Worksheets("Data").Range("Q10")
ActiveChart.Axes(xlValue).CrossesAt = 0
End Sub
我看不出有什么不对,只是Excel可能不喜欢组合图。我也无法在网上找到任何其他与类似问题相关的帖子,其中数据似乎格式正确并且实际存在于图表中,只是没有显示。任何帮助将不胜感激。