Excel Chart VBA Examples and Tutorials
Excel charts are one of the awesome tools available to represent the data in rich visualized graphs. Here are the most frequently used Excel Chart VBA Examples and Tutorials. You can access chart objects, properties and dealing with the methods.
Here are the top most Excel Chart VBA Examples and Tutorials, show you how to deal with chart axis, chart titles, background colors, chart data source, chart types, series and many other chart objects.
We can create the chart using different methods in Excel VBA, following are the various Excel Chart VBA Examples and Tutorials to show you creating charts in Excel using VBA.
1. Adding New Chart for Selected Data using Shapes.AddChart Method in Excel VBA
The following Excel Chart VBA Examples works similarly when we select some data and click on charts from Insert Menu and to create a new chart. This will create basic chart in an existing worksheet.
Sub ExAddingNewChartforSelectedData_Sapes_AddChart_Method()Range("C5:D7").SelectActiveSheet.Shapes.AddChart.SelectEnd Sub2. Adding New Chart for Selected Data using Charts.Add Method : Creating Chart Sheet in Excel VBA
The following Excel Chart VBA Examples method will add new chart into new worksheet by default. You can specify a location to embedded in a particular worksheet.
'Here is the other method to add charts using Chart Object. It will add a new chart for the selected data as new chart sheet.Sub ExAddingNewChartforSelectedData_Charts_Add_Method_SheetChart()Range("C5:D7").SelectCharts.AddEnd Sub3. Adding New Chart for Selected Data using Charts.Add Method : In Existing Sheet using Excel VBA
We can use the Charts.Add method to create a chart in existing worksheet. We can specify the position and location as shown below. This will create a new chart in a specific worksheet.
Sub ExAddingNewChartforSelectedData_Charts_Add_Method_InSheet()Range("C5:D7").SelectCharts.AddActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"End Sub4. Difference between embedded Chart and Chart Sheet in Excel:
Both are similar except event handlers, Chart Sheets will have the event handlers,we can write event programming for Chart Sheets. And the other type embedded charts can not support the event handlers. We can write classes to handle the events for the embedded chart, but not recommended.
We have seen multiple methods to create charts, but we cant set the chart at particular position using the above codes. You can use the ChartObjects.Add method to specify the position of the chart.
5. Adding New Chart for Selected Data using ChartObjects.Add Method in Excel VBA
ChartObjects.Add method is the best method as it is very easy to play with the chart objects to change the settings.
Sub ExAddingNewChartforSelectedData_ChartObjects_Add_Method()With ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300).Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")End WithEnd Sub6. Assigning Charts to an Object in Excel VBA
Here is another Excel Chart VBA Examples with ChartObjects, here we will assign to an Object and play with that.
Sub ExAddingNewChartforSelectedData_ChartObjects_Object()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")End Sub7. Changing the Chart Position in Excel VBA
The following VBA example will show you how to change the chart position.
Sub ExAddingNewChartforSelectedData_Object_Position()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")cht.Left = 350cht.Width = 400cht.Top = 30cht.Height = 200End Sub8. Align Chart Object at a Particular Range or Cell in Excel VBA
You can set the top,left, height and width properties of a chart object to align in a particular position.
Sub AlignChartAtParticularRange()' Chart AlignWith ActiveSheet.ChartObjects(1).Left = Range("A6").Left.Top = Range("A7").Top.Width = Range("D6").Left.Height = Range("D16").Top - Range("D6").TopEnd WithEnd Sub9. Use with statement while dealing with Charts and avoid the accessing the same object repeatedly in Excel VBA
If you are dealing with the same object, it is better to use with statement. It will make the program more clear to understand and executes faster.
Sub ExChartPostion_Object_Position()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Left = 350.Width = 400.Top = 30.Height = 200End WithEnd Sub10. You can use ActiveChart Object to access the active chart in Excel VBA
Active chart is the chart which is currently selected or activated in your active sheet.
Sub ExChartPostion_ActiveChart()ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300).ActivateWith ActiveChart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Parent.Left = 350.Parent.Width = 400.Parent.Top = 30.Parent.Height = 200End WithEnd SubExcel Chart VBA Examples and Tutorials – Setting Chart Types using Excel VBA:
We have verity of chart in Excel, we can use VBA to change and set the suitable chart type based on the data which we want to present. Below are the Excel Chart VBA Examples and Tutorials to change the chart type.
We can use Chart.Type property to set the chart type, here we can pass Excel chart constants or chart enumerations to set the chart type. Please refer the following table to understand the excel constants and enumerations.
11. Example to Change Chart type using Excel Chart Enumerations in Excel VBA
This Excel Chart VBA Example will use 1 as excel enumeration to plot the Aria Chart
Sub Ex_ChartType_Enumeration()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = 1 ' for aria chartEnd WithEnd Sub12. Example to Change Chart type using Excel Chart Constants in VBA
This Excel Chart VBA Example will use xlArea as excel constant to plot the Aria Chart.
Sub Ex_ChartType_xlConstant()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlAreaEnd WithEnd SubxlConstants is recommended than Excel Enumeration, as it is easy to understand and remember. Following are frequently used chart type examples:
13. Example to set the type as a Pie Chart in Excel VBA
The following VBA code using xlPie constant to plot the Pie chart.
Sub Ex_ChartType_Pie_Chart()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlPieEnd WithEnd Sub14. Example to set the chart type as a Line Chart in Excel VBA
The following VBA code using xlLine constant to plot the Pie chart.
Sub Ex_ChartType_Line_Chart()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlLineEnd WithEnd Sub15. Example to set the chart type as a Bar Chart in Excel VBA
The following VBA code using xlBar constant to plot the Pie chart.
Sub Ex_ChartType_Bar_Chart()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlBarEnd WithEnd Sub16. Example to set the chart type as a XYScatter Chart in Excel VBA
The following code using xlXYScatter constant to plot the Pie chart.
Sub Ex_ChartType_XYScatter_Chart()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlXYScatterEnd WithEnd SubExcel Chart VBA Examples and Tutorials – Formatting Chart Objects using Excel VBA:
Below are Excel Chart VBA Examples to show you how to change background colors of charts, series and changing the different properties of charts like Chart Legends, Line Styles, Number Formatting. You can also find the examples on Chart Axis and Chart Axes Setting and Number Formats.
17. Changing Chart Background Color – Chart Aria Interior Color in Excel VBA
The following VBA code will change the background color of the Excel Chart.
Sub Ex_ChartAriaInteriorColor()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.ChartArea.Interior.ColorIndex = 3End WithEnd Sub18. Changing PlotAria Background Color – PlotAria Interior Color in Excel VBA
The following code will change the background color of Plot Area in Excel VBA.
Sub Ex_PlotAriaInteriorColor()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.PlotArea.Interior.ColorIndex = 5End WithEnd Sub19.Changing Chart Series Background Color – Series Interior Color in Excel VBA
The following code is for changing the background color of a series using Excel VBA.
Sub Ex_SeriesInteriorColor()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.SeriesCollection(1).Format.Fill.ForeColor.RGB = rgbRed.Chart.SeriesCollection(2).Interior.ColorIndex = 5End WithEnd Sub20. Changing Chart Series Marker Style in Excel VBA
Here is the code to change the series marker style using Excel VBA, you can change to circle, diamond, square,etc. Check the excel constants and enumerations for more options available in excel vba.
Sub Ex_ChangingMarkerStyle()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlLine.Chart.SeriesCollection(1).MarkerStyle = 7End WithEnd Sub21. Changing Chart Series Line Style in Excel VBA
Here is the code to change the line color using Excel VBA, it will change the line style from solid to dash. Check the excel constants for more options.
Sub Ex_ChangingLineStyle()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlLine.Chart.SeriesCollection(1).Border.LineStyle = xlDashEnd WithEnd Sub22. Changing Chart Series Border Color in Excel VBA
Here is the code for changing series borders in Excel VBA.
Sub Ex_ChangingBorderColor()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlBar.Chart.SeriesCollection(1).Border.ColorIndex = 3End WithEnd Sub23. Change Chart Axis NumberFormat in Excel VBA
This code will change the chart axis number format using excel vba.
Sub Ex_ChangeAxisNumberFormat()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlLine.Chart.Axes(xlValue).TickLabels.NumberFormat = "0.00"End WithEnd Sub24. Formatting Axis Labels: Changing Axis Font to Bold using Excel VBA
The following example is for formating Axis labels using Excel VBA.
Sub Ex_ChangeAxisFormatFontBold()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlLine.Chart.Axes(xlCategory).TickLabels.Font.FontStyle = "Bold"End WithEnd Sub25. Two Y-axes Left and Right of Charts(Primary Axis and Secondary Axis) using Excel VBA
This code will set the series 2 into secondary Axis using Excel VBA.
Sub Ex_ChangeAxistoSecondary()Dim cht As ObjectSet cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)With cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7").Chart.Type = xlLine.Chart.SeriesCollection(2).AxisGroup = 2End WithEnd SubExcel Chart VBA Examples and Tutorials – Chart Collection in Excel VBA
You can use ChartObject Collection to loop through the all charts in worksheet or workbook using Excel VBA. And do whatever you want to do with that particular chart. Here are Excel Chart VBA Examples to deal with Charts using VBA.
26. Set equal widths and heights for all charts available in a Worksheet using Excel VBA
Following is the Excel VBA code to change the chart width and height.
Sub Ex_ChartCollections_Change_widths_heights()Dim cht As ObjectFor Each cht In ActiveSheet.ChartObjectscht.Width = 400cht.Height = 200NextEnd Sub27. Delete All Charts in a Worksheet using Excel VBA
Following is the Excel VBA example to delete all charts in worksheet.
Sub Ex_DeleteAllCharts()Dim cht As ObjectFor Each cht In ActiveSheet.ChartObjectscht.DeleteNextEnd SubExcel Chart VBA Examples and Tutorials – Other useful Examples and tutorials on Excel VBA Charting
28. Set Chart Data Source using Excel VBA
Below is the Excel Chart VBA Example to set the chart data source. You can set it by using .SetSourceData Source property of a chart
Sub Ex_ChartDataSource()Dim cht As Chart'Add new chartActiveSheet.Shapes.AddChart.SelectWith ActiveChart'Specify source data and orientation.SetSourceData Source:=Sheet1.Range("A1:C5")End WithEnd Sub29. Swap or Switch Rows and Columns in Excel Charts using VBA
Here is the excel VBA code to swap the Rows to Columns.
Sub Ex_SwitchRowsColumns()Dim cht As Chart'Add new chartActiveSheet.Shapes.AddChart.SelectWith ActiveChart'Specify source data and orientation.SetSourceData Source:=Sheets("Temp").Range("C5:D7"), PlotBy:=xlRows ' you can use xlColumns to swith itEnd WithEnd Sub30. Set Chart Data Labels and Legends using Excel VBA
You can set Chart Data Labels and Legends by using SetElement property in Excl VBA
Sub Ex_AddDataLabels()Dim cht As Chart'Add new chartActiveSheet.Shapes.AddChart.SelectWith ActiveChart'Specify source data and orientation.SetSourceData Source:=Sheet1.Range("A1:B5"), PlotBy:=xlColumns'Set Chart type.ChartType = xlPie'set data label at center.SetElement (msoElementDataLabelCenter)'set legend at bottom.SetElement (msoElementLegendBottom)End WithEnd Sub31. Changing Axis Titles of a Chart in Excel VBA
Following is the code to change the chart Axis titles using Excel VBA..
Sub Ex_ChangeAxisTitles()activechart.chartobjects(1).activateActiveChart.Axes(xlCategory).HasTitle = TrueActiveChart.Axes(xlCategory).AxisTitle.Text = "Quarter"ActiveChart.Axes(xlValue).HasTitle = TrueActiveChart.Axes(xlValue).AxisTitle.Text = "Sales"End Sub32. Change Titles of a Chart using Excel VBA
Following is the code to change the chart titles using Excel VBA..
Sub Ex_ChangeChartTitles()ActiveSheet.ChartObjects(1).ActivateActiveChart.HasTitle = TrueActiveChart.ChartTitle.Text = "Overal Summary"End Sub33. Send an Excel Chart to an Outlook email using VBA
Following is the code to Send an Excel Chart to an Outlook email using VBA.
Sub SendChartThroughMail()'Add refernce to Microsoft Outlook object LibraryDim olMail As MailItemDim objOL As ObjectDim sImgPath As StringDim sHi As StringDim sBody As StringDim sThanks As String' Saving chart as imagesImgPath = ThisWorkbook.Path & "\Temp_" & Format(Now(), "DD_MM_YY_HH_MM_SS") & ".bmp"Sheets("Sheet1").ChartObjects(1).Chart.Export sImgPath'sending the emailSet objOL = CreateObject("Outlook.Application")Set olMail = objOL.CreateItem(olMailItem)With olMail.To = "youremail@orgdomain.com".Subject = "Test Mail with chart".Attachments.Add sImgPath.HTMLBody = sHi & sBody & sThanks.DisplayEnd With'Delete the saved chartKill sImgPath'Free-up the objectsSet olMail = NothingSet olApp = NothingEnd Sub