Excel is a powerful tool for data analysis, and Visual Basic for Applications (VBA) is a powerful programming language that you can use within Excel to automate many tasks. One common task that you can automate with VBA is creating charts. In this article, we'll show you how to create charts in VBA in Excel.
There are two main types of charts that you can create in Excel:
Creating a 2D chart in VBA is relatively simple. First, you need to create a Chart object. This is the container that will hold your chart. Then, you need to add a Series object to the Chart object. The Series object contains the data that will be plotted on the chart.
Here's an example of how to create a basic bar chart:
Sub CreateChart()
'Create a new Chart object
Dim cht As Chart
Set cht = ActiveSheet.Shapes.AddChart2(201, xlBarClustered).Chart
'Add a Series object to the Chart object
Dim srs As Series
Set srs = cht.SeriesCollection.NewSeries
'Set the Series values equal to an array of values
srs.Values = Array(1, 2, 3)
'Set the Series name equal to a string value
srs.Name = "My Series"
'Set the x-axis labels equal to an array of string values
cht.Axes(xlCategory).CategoryNames = Array("Label 1", "Label 2", "Label 3")
End Sub