Excel VBA单图表绘双系列问题:第二个系列仅显图例无数据
解决Excel VBA图表中第二个数据系列不显示的问题
问题出在直接用一维数组给系列的XValues和Values赋值时,Excel无法正确解析数据(尤其是日期类型的X轴值),导致系列仅在图例显示但图表上无数据。以下是两种可行的修复方案:
方案1:使用工作表临时单元格存储数据
把最大值系列的两个点数据写入工作表的临时区域,再通过引用单元格范围赋值,Excel能准确识别数据类型:
Sub FixedWithCells() Dim test_sheet As Worksheet Set test_sheet = ThisWorkbook.Worksheets("TestData") Dim ch As Chart test_sheet.ChartObjects.Add Left:=750, Top:=50, Width:=400, Height:=300 Set ch = test_sheet.ChartObjects(1).Chart Dim ser As Series Set ser = ch.SeriesCollection.NewSeries ser.ChartType = xlLine ser.XValues = test_sheet.Range("F2:F278") ser.Values = test_sheet.Range("K2:K278") ser.Name = "Running Total" Dim max_val As Double max_val = 175000 Set ser = ch.SeriesCollection.NewSeries ser.ChartType = xlLine Dim min_date As Date Dim max_date As Date min_date = test_sheet.Range("F2").Value max_date = test_sheet.Cells(278, 6).Value ' 写入临时单元格(可选择不显眼的列,比如AA/AB) test_sheet.Range("AA1").Value = min_date test_sheet.Range("AA2").Value = max_date test_sheet.Range("AB1").Value = max_val test_sheet.Range("AB2").Value = max_val ' 引用单元格范围作为系列数据 ser.XValues = test_sheet.Range("AA1:AA2") ser.Values = test_sheet.Range("AB1:AB2") ser.Name = "Maximum" End Sub
方案2:使用二维数组并转换日期为序列号
Excel内部用数字(序列号)存储日期,直接传递日期对象可能导致解析错误,同时图表系列需要二维数组来正确识别数据:
Sub FixedWith2DArray() Dim test_sheet As Worksheet Set test_sheet = ThisWorkbook.Worksheets("TestData") Dim ch As Chart test_sheet.ChartObjects.Add Left:=750, Top:=50, Width:=400, Height:=300 Set ch = test_sheet.ChartObjects(1).Chart Dim ser As Series Set ser = ch.SeriesCollection.NewSeries ser.ChartType = xlLine ser.XValues = test_sheet.Range("F2:F278") ser.Values = test_sheet.Range("K2:K278") ser.Name = "Running Total" Dim max_val As Double max_val = 175000 Set ser = ch.SeriesCollection.NewSeries ser.ChartType = xlLine Dim min_date As Date Dim max_date As Date min_date = test_sheet.Range("F2").Value max_date = test_sheet.Cells(278, 6).Value ' 将日期转为Excel序列号,并用二维数组赋值 ser.XValues = Array(Array(CDbl(min_date)), Array(CDbl(max_date))) ser.Values = Array(Array(max_val), Array(max_val)) ser.Name = "Maximum" End Sub
两种方案都能让第二个系列正常显示在图表上,方案1更直观易维护,方案2无需占用工作表单元格。
内容的提问来源于stack exchange,提问作者teddybouch
相关产品推荐
相关产品推荐

