Creating Graphs With Excel VBA

In this example we are going to create an excel chart with VBA code. To achieve this we are going to start with a table of data. This doesn't need to be static or predefined, this table could be generated from your code, but for this example we will just create a example data set.



To create the following code I used the record macro function. If you try this yourself you will likely find that your code is much longer than mine posted below. I have removed some unnecessary lines of code that do not perform a useful function, such as moving the screen or repeated selections. I recommend getting used to using the macro tool and reworking the recorded code.



This produces the following chart. when editing the code above it is recommended to make small changes and test your code regularly when starting to learn new concepts. This approach allows for easier debugging as you can identify the likely place where an error has occurred.

Code:
Sub createGraph()
'
' createGraph Macro
'

'
    Range("C2:D6").Select
    ActiveSheet.Shapes.AddChart2(240, xlXYScatterLines).Select
    ActiveChart.SetSourceData Source:=Range("Sheet1!$C$2:$D$6")
    ActiveChart.ChartTitle.Select
    ActiveChart.ChartTitle.Text = "Money Plan"
    Selection.Format.TextFrame2.TextRange.Characters.Text = "Money Plan"

    ActiveChart.ChartArea.Select
    ActiveChart.FullSeriesCollection(1).Trendlines.Add
    ActiveChart.FullSeriesCollection(1).Trendlines(1).Select
    Selection.Type = xlPower
    Selection.DisplayEquation = True
    Selection.DisplayRSquared = True
    Application.CommandBars("Format Object").Visible = False
    ActiveChart.FullSeriesCollection(1).Trendlines(1).DataLabel.Select
    ActiveChart.ChartArea.Select
    
    
End Sub




Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.



Must Read Articles


VBA and Microsoft Excel - Getting the most out of excel with VBA programming
VBA and Microsoft Word - Getting the most out of word with VBA programming
Application Object - Using the applications features in your code.
Installing VBA and First Program - What do you need to start using visual basic application VBA.