VBA 使えるソースコード

つたないソースコードを載せます。これは、他人の書いたソースコードを読む練習に最適です。初心者の方は、どうしたらきれいになるかなど考えながら活用してください。

VBA 4種類のデータの比較を自動でしよう

Option Explicit

Sub fig_kinds_4()
'
' fig_kinds_4 Macro
' 4種類のデータの比較を行います。
'

'
Dim title As String
title = InputBox(" グラフタイトルを入力してください。")

Dim n As Integer: n = 0

Do Until Cells(n + 5, 1).Value = ""
n = n + 1
Loop

Cells(2, 7).Value = n


Range("B6:B" & n + 4).Select
ActiveSheet.Shapes.AddChart2(240, xlXYScatterLines).Select
ActiveChart.SetSourceData Source:=Range("Sheet2!$B$6:$B$" & n + 4)
'Application.CutCopyMode = False
ActiveChart.FullSeriesCollection(1).Name = Cells(5, 2).Value
ActiveChart.FullSeriesCollection(1).XValues = "=Sheet2!$A$6:$A$" & n + 4
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(2).Name = Cells(5, 3).Value
ActiveChart.FullSeriesCollection(2).XValues = "=Sheet2!$A$6:$A$" & n + 4
ActiveChart.FullSeriesCollection(2).Values = "=Sheet2!$C$6:$C$" & n + 4
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(3).Name = Cells(5, 4).Value
ActiveChart.FullSeriesCollection(3).XValues = "=Sheet2!$A$6:$A$" & n + 4
ActiveChart.FullSeriesCollection(3).Values = "=Sheet2!$D$6:$D$" & n + 4
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(4).Name = Cells(5, 5).Value
ActiveChart.FullSeriesCollection(4).XValues = "=Sheet2!$A$6:$A$" & n + 4
ActiveChart.FullSeriesCollection(4).Values = "=Sheet2!$E$6:$E$" & n + 4
ActiveChart.SetElement (msoElementLegendRight)

ActiveChart.Axes(xlCategory, xlPrimary).HasTitle = True
ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = Cells(2, 2).Value
ActiveChart.Axes(xlValue, xlPrimary).HasTitle = True
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = Cells(2, 4).Value
ActiveSheet.ChartObjects(1).Chart.HasTitle = True
ActiveSheet.ChartObjects(1).Chart.ChartTitle.Text = title
End Sub

 

結果 ↓  グラフを作成しました

f:id:yoronx:20200307170216p:plain