如何在现有图表上添加垂直线?

问题描述

我尝试应用我在网上找到的内容,但无法将其应用到我的代码中。 x 轴给我带来了一些问题,我无法选择图表上 x 轴上的现有点(请参阅突出显示的行)。我这样做的方式是创建一个具有 2 个值的新 x 轴。

' Create an empty Chart
Sheet1.Shapes.AddChart2.Select
Sheet1.ChartObjects(1).Name = "Workforce"
' Chart Parent (ChartObject)
ActiveChart.Parent.Left = 160
ActiveChart.Parent.Top = 160
ActiveChart.Parent.Width = 1080
ActiveChart.Parent.Height = 360
ActiveChart.ChartArea.RoundedCorners = True
ActiveChart.ChartArea.Border.ColorIndex = 1
' Chart Type
ActiveChart.ChartType = xlLineMarkers
' Chart Source
ActiveChart.SetSourceData Source:=Range("Project!$N$1:$BN$3")
' Chart Title
ActiveChart.ChartTitle.Text = "Workforce in Department"
' Chart Legend
ActiveChart.HasLegend = True
ActiveChart.Legend.Position = xlLegendPositionTop
' Chart Axis X
ActiveChart.Axes(xlCategory).HasTitle = True
ActiveChart.Axes(xlCategory).AxisTitle.Text = "53 Weeks in Year " & Right(Sheet3.Cells(1,5).Value,4)
' Chart Axis Y
ActiveChart.Axes(xlValue).HasTitle = True
ActiveChart.Axes(xlValue).AxisTitle.Text = "Number of Scientist"
' Chart Series
' Serie Theory Data
ActiveChart.SeriesCollection(1).Select
Selection.Border.ColorIndex = 5
Selection.Border.Weight = xlThin
Selection.Border.Linestyle = xlDot
Selection.MarkerBackgroundColor = RGB(0,0)
Selection.MarkerForegroundColor = RGB(0,0)
Selection.Name = "Theory"
' Serie Reality Data
ActiveChart.SeriesCollection(2).Select
Selection.Border.ColorIndex = 5
Selection.Border.Weight = xlThin
Selection.Border.Linestyle = xlContinuous
Selection.MarkerBackgroundColor = RGB(0,255)
Selection.MarkerForegroundColor = RGB(0,255)
Selection.Name = "Reality"
' Serie Wanted Data
ActiveChart.SeriesCollection(3).Select
Selection.Border.ColorIndex = 3
Selection.Border.Weight = xlThin
Selection.Border.Linestyle = xlDot
Selection.MarkerBackgroundColor = RGB(255,0)
Selection.MarkerForegroundColor = RGB(255,0)
Selection.Name = "Wanted"
' Y axis adjusted
Dim n As Integer
n = Application.WorksheetFunction.Sum(Sheet3.Range("N1:BN1")) / 53
Sheet1.ChartObjects(1).Select
ActiveChart.Axes(xlValue).MinimumScale = n - 15
Sheet1.ChartObjects(1).Select
ActiveChart.Axes(xlValue).MaximumScale = n + 5
' Vertical line
Dim ns As Series
Sheet1.ChartObjects(1).Select
ActiveChart.SeriesCollection.NewSeries.Name = "=""Current week"""
Set ns = ActiveChart.SeriesCollection("Current week")
ns.XValues = Array(11,11)   '<======= PROBLEM! ==================================
ns.Values = Array(n - 15,n + 5)

我想放置一个变量而不是数字 11,但首先我必须让它使用这个数字(第 11 周)。 像往常一样,欢迎任何想法。 谢谢

解决方法

尝试添加这两行。

ns.ChartType = xlXYScatterLines
ns.AxisGroup = xlPrimary