Dim mySheet As Worksheet
Set mySheet = Thisworkbook.Worksheets(1)
Dim currentChart As chart
Set currentChart = mySheet.ChartObjects("グラフ 3").chart
currentChart.setSourceData Source:=mySheet.Range("A1:B3500")
ここで問題になるのが「グラフ 3」というオブジェクト名で、
- Excel上で確認・変更できない(VBAで取得する必要がある)
- 別ブックにコピーすると、オブジェクト名が勝手に変更される
問題があります。そこで、分かりやすいグラフタイトル(ユーザーが任意に追加・変更するものです)を利用できるクラスモジュールを作成しました。
もちろん、シート内に同じタイトルのグラフは作成しないようにしてくださいね。

クラスモジュール
最初に関数setSheet(Worksheet)を実行すると、シートにあるChartObjectを全て検索し、グラフタイトルをキーとしてDictionary変数graphSetに格納します。これが成功すれば、getNameでグラフタイトルからオブジェクト名を検索でき、様々な操作が可能です。代表的な、データ元の範囲設定と、x軸の最小・最大値設定関数を例として作成しました。
必要に応じて、タイトルがない場合無視する等の処理を加えてください。
Option Explicit
Private graphSet As Dictionary
Private targetSheet As Worksheet
Public Function setSheet(mySheet As Worksheet)
Set targetSheet = mySheet
With targetSheet
Set graphSet = New Dictionary
Dim chart
For Each chart In targetSheet.ChartObjects
graphSet.Add chart.chart.ChartTitle.Text, chart.Name
Next
End With
End Function
Public Function getName(GraphTitle)
getName = graphSet(GraphTitle)
End Function
Public Function setSourceData(GraphTitle, StartColumn, NumOfColumn)
With targetSheet
Dim lastRow
lastRow = .Cells(.Rows.Count, StartColumn).End(xlUp).Row
Dim currentChart As chart
Set currentChart = .ChartObjects(getName(GraphTitle)).chart
currentChart.setSourceData Source:=.Range(.Cells(1, StartColumn), .Cells(lastRow, StartColumn + NumOfColumn - 1))
End With
End Function
Public Function setCategoryMinMax(GraphTitle, MinScale, MaxScale)
With targetSheet
Dim currentChart As chart
Set currentChart = .ChartObjects(getName(GraphTitle)).chart
currentChart.Axes(xlCategory).MinimumScale = MinScale
currentChart.Axes(xlCategory).MaximumScale = MaxScale
End With
End Function
標準モジュール【使用例】
Set targetSheet = Thisworkbook.Worksheets(1)
Dim graphs As New chartsInSheet
graphs.setSheet targetSheet
graphs.setSourceData "帝国都市人口-魔導士数相関図", 1, 2
graphs.setCategoryMinMax "帝国魔導士による撃墜数時系列", startTimeSerial, endTimeSerial
※setSourceDataはデータの最終行を検索し、指定した列数を範囲とします。
※setCategoryMinMaxは数値で指定しますが、日付はシリアル値で代入する必要があります(Excelの仕様より)。

0 件のコメント:
コメントを投稿