2024年12月30日 星期一

vba:畫垂直線 解說版

新改好的:

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


沒有留言:

張貼留言

職場毒癌:你憑什麼以為你十年寒窗,抵得我三代從商

你憑什麼以為你十年寒窗,抵得我三代從商——這句話已經記不得是從哪裡看到的,可能是某部劇,也可能是某篇 FB 文章標題。 但最近,特別有感。 為什麼會有這種感觸? 職場上有個同事,一路慢慢升到課長,好歹也是管理職,雖說不上鐵飯碗,但在多數人眼裡也算穩定。 結果呢?輾轉換了兩個製造課...