OfficeType

VBA~基準線の上下で背景色を分けよう~Excel

VBAでグラフの基準線の上下で背景色を分ける方法を解説します。

下の画像において下のコードを実行するとグラフの基準線の上下で背景色を分けることができます。

image-01

Sub test1()
Dim kijun As Long

kijun = 5


With ActiveSheet.Shapes.AddChart.Chart

.ChartType = xlColumnClustered
.SetSourceData Range(Range("A3"), Range("B9"))

With .SeriesCollection.NewSeries
.Values = Array(kijun, kijun)
.ChartType = xlArea
.AxisGroup = 2
.Interior.Color = RGB(222, 235, 247)
End With

.Axes(xlValue, 2).MinimumScale = .Axes(xlValue, 1).MinimumScale
.Axes(xlValue, 2).MaximumScale = .Axes(xlValue, 1).MaximumScale
.Axes(xlValue, 2).TickLabelPosition = xlNone

.HasAxis(xlCategory, 2) = True
.Axes(xlCategory, 2).AxisBetweenCategories = False
.Axes(xlCategory, 2).TickLabelPosition = xlNone

.PlotArea.Interior.Color = RGB(197, 224, 180)

.HasLegend = False

.HasTitle = True
.ChartTitle.Text = "月間売上個数"

End With

End Sub

コードの説明

Dim kijun As Long

kijunという変数は整数であると定義しています。

kijun = 5

kijunという変数に5を格納しています。基準線の基準値を変えたい場合はこの数値を変えてください。

Withから最後のEnd Withまでがグラフの作成、設定です。

ActiveSheet.Shapes.AddChart.Chart

グラフエリアを追加しています。

image-02

.ChartType = xlColumnClustered

グラフの種類を設定しています。xlColumnClusteredは棒グラフの集合縦棒になります。

image-03

.SetSourceData Range(Range("A3"), Range("B9"))

グラフのデータ範囲を設定しています。

With .SeriesCollection.NewSeries
.Values = Array(kijun, kijun)
.ChartType = xlArea
.AxisGroup = 2
.Interior.Color = RGB(222, 235, 247)
End With

基準線の系列を追加しています。

image-04

.Values = Array(kijun, kijun)

基準線が直線になるように2つのデータを両方とも先ほど設定した変数kijunに設定してます。つまり両方とも5になります。

image-05

.ChartType = xlArea

グラフの種類を設定しています。xlAreaは面になります。

image-06

.AxisGroup = 2

基準線の系列を第2軸に設定しています。

image-07

.Interior.Color = RGB(222, 235, 247)

面の色を水色に設定してます。

image-08

.Axes(xlValue, 2).MinimumScale = .Axes(xlValue, 1).MinimumScale

第2縦軸(基準線の軸)の目盛の最小値を、第1縦軸(データの軸)の最小値に設定してます。

image-09

.Axes(xlValue, 2).MaximumScale = .Axes(xlValue, 1).MaximumScale

第2縦軸(基準線の軸)の目盛の最大値を、第1縦軸(データの軸)の最大値に設定してます。

image-10

.Axes(xlValue, 2).TickLabelPosition = xlNone

第2縦軸のラベルを、なしに設定しています。

image-11

.HasAxis(xlCategory, 2) = True

第2横軸を表示しています。

image-12

.Axes(xlCategory, 2).AxisBetweenCategories = False

第2横軸の軸位置を目盛に設定しています。

image-13

.Axes(xlCategory, 2).TickLabelPosition = xlNone

第2横軸のラベルを、なしに設定しています。

image-14

.PlotArea.Interior.Color = RGB(197, 224, 180)

プロットエリアの色を黄緑に設定しています。

image-15

.HasLegend = False

凡例を非表示に設定してます。

image-16

.HasTitle = True

タイトルの要素を追加しています。

image-17

.ChartTitle.Text = "月間売上個数"

タイトルを月間売上個数に設定しています。

image-18