Excelでマクロを使用して散布図またはバブルチャートのデータポイントにラベルを追加する方法 http://support.microsoft.com/kb/213750/ja
以下の各食材100gあたりの栄養価のデータを散布図にします.横軸にカロリー(kCal),縦軸にタンパク質(g)を示します.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ラベル カロリー タンパク質 | |
トマト 18 0.88 | |
バナナ 89 1.09 | |
ミカン 53 0.81 | |
リンゴ 48 0.27 | |
キュウリ 16 0.65 |
データをシートに記入したら散布図の挿入
こんなかんじでグラフが作成されます.タイトルは消した!
ツール > マクロ > Visual Basic Editorを起動
プロジェクトエクスプローラーで該当のシートを右クリックして標準モジュールを追加
以下のコードを記入
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sub AttachLabelsToPoints() | |
'Dimension variables. | |
Dim RCounter As Integer, CCounter As Integer, xVals As String | |
'Disable screen updating while the subroutine is run. | |
Application.ScreenUpdating = False | |
'Store the formula for the first series in "xVals". | |
xVals = ActiveChart.SeriesCollection(1).Formula | |
'Extract the range for the data from xVals. | |
xVals = Mid(xVals, InStr(InStr(xVals, ","), xVals, _ | |
Mid(Left(xVals, InStr(xVals, "!") - 1), 9))) | |
xVals = Left(xVals, InStr(InStr(xVals, "!"), xVals, ",") - 1) | |
Do While Left(xVals, 1) = "," | |
xVals = Mid(xVals, 2) | |
Loop | |
'Attach a label to each data point in the chart. | |
For RCounter = 1 To Range(xVals).Cells.Count | |
For CCounter = 1 To ActiveChart.SeriesCollection.Count | |
ActiveChart.SeriesCollection(CCounter).Points(RCounter).HasDataLabel = _ | |
True | |
ActiveChart.SeriesCollection(CCounter).Points(RCounter).DataLabel.Text = _ | |
Range(xVals).Cells(RCounter, 1).Offset(0, -1).Value | |
Next CCounter | |
Next RCounter | |
End Sub |
ラベルを追加するグラフを選択して実行
Excelに戻ってツール → マクロ → マクロからも実行できます
でこんな感じ
X軸,y軸にラベル貼りゃよかった
参考にしたサイトのものではデータが2列以上あると追加されないのですが,上のコードなら大丈夫,のはず.いろいろいじればいろいろいじれます.コードはWindowsでも使えると思う.