新改好的:
Sub 巨集3V2(Name, rngXValues, 垂直線)
If InStr(Name, "Chart") > 0 Then
ActiveSheet.ChartObjects(Name).Activate
ActiveChart.PlotArea.Select
Application.CutCopyMode = False
Application.CutCopyMode = False
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).Values = "=" & ActiveSheet.Name & "!" & 垂直線.Address
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).Name = "=""垂直線"""
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).XValues = "=" & ActiveSheet.Name & "!" & rngXValues.Address
ActiveChart.Axes(xlValue).MajorGridlines.Select
ActiveChart.ChartArea.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count - 1).ChartType = xlLine
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).ChartType = xlColumnClustered
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).AxisGroup = 2
End If
End Sub
好的,讓我們逐一分別來解說這段 VBA 代碼。這段代碼的作用是:
主要功能是在 Excel 中的一個圖表裡添加一條垂直線。
這個子程序有三個參數:
Sub 巨集3V2(Name, rngXValues, 垂直線)
Name:圖表名稱
rngXValues:X 軸數據範圍
垂直線:垂直線的數據範圍
檢查圖表名稱:
If InStr(Name, "Chart") > 0 Then
如果圖表名稱包含“Chart”,則繼續執行。
選擇並啟用指定的圖表:
ActiveSheet.ChartObjects(Name).Activate
ActiveChart.PlotArea.Select
Application.CutCopyMode = False
增加新數據:
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).Values = "=" & ActiveSheet.Name & "!" & 垂直線.Address
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).Name = "=""垂直線"""
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).XValues = "=" & ActiveSheet.Name & "!" & rngXValues.Address
新增一個數據系列,並設置它的數據範圍為 垂直線。
設置這個數據系列的名稱為 “垂直線”。
設置 X 軸數據範圍為 rngXValues。
設定圖表類型:
ActiveChart.Axes(xlValue).MajorGridlines.Select
ActiveChart.ChartArea.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count - 1).ChartType = xlLine
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).ChartType = xlColumnClustered
ActiveChart.FullSeriesCollection(ActiveChart.SeriesCollection.Count).AxisGroup = 2
設置圖表類型為群組柱狀圖。
將倒數第二個數據系列(即原有的數據)設為折線圖。
將新的垂直線數據系列設為次坐標軸。
結束條件結構與結束SUB:
End If
End Sub
沒有留言:
張貼留言