Vba excel создать диаграмму

Программное создание графика (диаграммы) в VBA Excel с помощью метода Charts.Add на основе данных из диапазона ячеек на рабочем листе. Примеры.

Метод Charts.Add

В настоящее время на сайте разработчиков описывается метод Charts.Add2, который, очевидно, заменил метод Charts.Add. Тесты показали, что Charts.Add продолжает работать в новых версиях VBA Excel, поэтому в примерах используется именно он.

Синтаксис

Charts.Add ([Before], [After], [Count])

Charts.Add2 ([Before], [After], [Count], [NewLayout])

Параметры

Параметры методов Charts.Add и Charts.Add2:

Параметр Описание
Before Имя листа, перед которым добавляется новый лист с диаграммой. Необязательный параметр.
After Имя листа, после которого добавляется новый лист с диаграммой. Необязательный параметр.
Count Количество добавляемых листов с диаграммой. Значение по умолчанию – 1. Необязательный параметр.
NewLayout Если NewLayout имеет значение True, диаграмма вставляется с использованием новых правил динамического форматирования (заголовок имеет значение «включено», а условные обозначения – только при наличии нескольких рядов). Необязательный параметр.

Если параметры Before и After опущены, новый лист с диаграммой вставляется перед активным листом.

Примеры

Таблицы

В качестве источников данных для примеров используются следующие таблицы:

Исходные таблицы для создания диаграмм

Пример 1

Программное создание объекта Chart с типом графика по умолчанию и по исходным данным из диапазона «A2:B26»:

Sub Primer1()

Dim myChart As Chart

‘создаем объект Chart с расположением нового листа по умолчанию

Set myChart = ThisWorkbook.Charts.Add

    With myChart

        ‘назначаем объекту Chart источник данных

        .SetSourceData (Sheets(«Лист1»).Range(«A2:B26»))

        ‘переносим диаграмму на «Лист1» (отдельный лист диаграммы удаляется)

        .Location xlLocationAsObject, «Лист1»

    End With

End Sub

Результат работы кода VBA Excel из первого примера:

Объект Chart с типом графика по умолчанию

Пример 2

Программное создание объекта Chart с двумя линейными графиками по исходным данным из диапазона «A2:C26»:

Sub Primer2()

Dim myChart As Chart

Set myChart = ThisWorkbook.Charts.Add

    With myChart

        .SetSourceData (Sheets(«Лист1»).Range(«A2:C26»))

        ‘задаем тип диаграммы (линейный график с маркерами)

        .ChartType = xlLineMarkers

        .Location xlLocationAsObject, «Лист1»

    End With

End Sub

Результат работы кода VBA Excel из второго примера:

Объект Chart с двумя линейными графиками (с маркерами)

Пример 3

Программное создание объекта Chart с круговой диаграммой, разделенной на сектора, по исходным данным из диапазона «E2:F7»:

Sub Primer3()

Dim myChart As Chart

Set myChart = ThisWorkbook.Charts.Add

    With myChart

        .SetSourceData (Sheets(«Лист1»).Range(«E2:F7»))

        ‘задаем тип диаграммы (пирог — круг, разделенный на сектора)

        .ChartType = xlPie

        ‘задаем стиль диаграммы (с отображением процентов)

        .ChartStyle = 261

        .Location xlLocationAsObject, «Лист1»

    End With

End Sub

Результат работы кода VBA Excel из третьего примера:

Объект Chart с круговой диаграммой

Примечание

В примерах использовались следующие методы и свойства объекта Chart:

Компонент Описание
Метод SetSourceData Задает диапазон исходных данных для диаграммы.
Метод Location Перемещает диаграмму в заданное расположение (новый лист, существующий лист, элемент управления).
Свойство ChartType Возвращает или задает тип диаграммы. Смотрите константы.
Свойство ChartStyle Возвращает или задает стиль диаграммы. Значение нужного стиля можно узнать, записав макрос.

In this Article

  • Creating an Embedded Chart Using VBA
  • Specifying a Chart Type Using VBA
  • Adding a Chart Title Using VBA
  • Changing the Chart Background Color Using VBA
  • Changing the Chart Plot Area Color Using VBA
  • Adding a Legend Using VBA
  • Adding Data Labels Using VBA
  • Adding an X-axis and Title in VBA
  • Adding a Y-axis and Title in VBA
  • Changing the Number Format of An Axis
  • Changing the Formatting of the Font in a Chart
  • Deleting a Chart Using VBA
  • Referring to the ChartObjects Collection
  • Inserting a Chart on Its Own Chart Sheet

Excel charts and graphs are used to visually display data. In this tutorial, we are going to cover how to use VBA to create and manipulate charts and chart elements.

You can create embedded charts in a worksheet or charts on their own chart sheets.

Creating an Embedded Chart Using VBA

We have the range A1:B4 which contains the source data, shown below:

The Source Data For the Chart

You can create a chart using the ChartObjects.Add method. The following code will create an embedded chart on the worksheet:

Sub CreateEmbeddedChartUsingChartObject()

Dim embeddedchart As ChartObject

Set embeddedchart = Sheets("Sheet1").ChartObjects.Add(Left:=180, Width:=300, Top:=7, Height:=200)
embeddedchart.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B4")

End Sub

The result is:

Creating a Chart using VBA and the ChartObjects method

You can also create a chart using the Shapes.AddChart method. The following code will create an embedded chart on the worksheet:

Sub CreateEmbeddedChartUsingShapesAddChart()

Dim embeddedchart As Shape

Set embeddedchart = Sheets("Sheet1").Shapes.AddChart
embeddedchart.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B4")

End Sub

Specifying a Chart Type Using VBA

We have the range A1:B5 which contains the source data, shown below:

The Source range for Creating a Pie Chart Using VBA

You can specify a chart type using the ChartType Property. The following code will create a pie chart on the worksheet since the ChartType Property has been set to xlPie:

Sub SpecifyAChartType()

Dim chrt As ChartObject

Set chrt = Sheets("Sheet1").ChartObjects.Add(Left:=180, Width:=270, Top:=7, Height:=210)
chrt.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B5")
chrt.Chart.ChartType = xlPie

End Sub

The result is:
Specifying the Chart Type in VBA

These are some of the popular chart types that are usually specified, although there are others:

  • xlArea
  • xlPie
  • xlLine
  • xlRadar
  • xlXYScatter
  • xlSurface
  • xlBubble
  • xlBarClustered
  • xlColumnClustered

Adding a Chart Title Using VBA

We have a chart selected in the worksheet as shown below:

The Active Chart

You have to add a chart title first using the Chart.SetElement method and then specify the text of the chart title by setting the ChartTitle.Text property.

The following code shows you how to add a chart title and specify the text of the title of the Active Chart:

Sub AddingAndSettingAChartTitle()

ActiveChart.SetElement (msoElementChartTitleAboveChart)
    ActiveChart.ChartTitle.Text = "The Sales of the Product"
    
End Sub

The result is:

Chart with title added using VBA

Note: You must select the chart first to make it the Active Chart to be able to use the ActiveChart object in your code.

Changing the Chart Background Color Using VBA

We have a chart selected in the worksheet as shown below:

Active Chart Changing Background Color

You can change the background color of the entire chart by setting the RGB property of the FillFormat object of the ChartArea object. The following code will give the chart a light orange background color:

Sub AddingABackgroundColorToTheChartArea()

ActiveChart.ChartArea.Format.Fill.ForeColor.RGB = RGB(253, 242, 227)

End Sub

The result is:

Changing the Chart Background Color in VBA

You can also change the background color of the entire chart by setting the ColorIndex property of the Interior object of the ChartArea object. The following code will give the chart an orange background color:

Sub AddingABackgroundColorToTheChartArea()

ActiveChart.ChartArea.Interior.ColorIndex = 40

End Sub

The result is:
Changing the Chart Background Color in VBA with ColorIndex

Note: The ColorIndex property allows you to specify a color based on a value from 1 to 56, drawn from the preset palette, to see which values represent the different colors, click here.

Changing the Chart Plot Area Color Using VBA

We have a chart selected in the worksheet as shown below:

Selected Chart For Changing the Plot Area Color

You can change the background color of just the plot area of the chart, by setting the RGB property of the FillFormat object of the PlotArea object. The following code will give the plot area of the chart a light green background color:

Sub AddingABackgroundColorToThePlotArea()

ActiveChart.PlotArea.Format.Fill.ForeColor.RGB = RGB(208, 254, 202)
    
End Sub

The result is:
Changing the Plot Area color Using VBA

Adding a Legend Using VBA

We have a chart selected in the worksheet, as shown below:

Selected Chart for Changing the Legend

You can add a legend using the Chart.SetElement method. The following code adds a legend to the left of the chart:

Sub AddingALegend()

ActiveChart.SetElement (msoElementLegendLeft)

End Sub

The result is:
Adding A Legend to the Chart Using VBA

You can specify the position of the legend in the following ways:

  • msoElementLegendLeft – displays the legend on the left side of the chart.
  • msoElementLegendLeftOverlay – overlays the legend on the left side of the chart.
  • msoElementLegendRight – displays the legend on the right side of the chart.
  • msoElementLegendRightOverlay – overlays the legend on the right side of the chart.
  • msoElementLegendBottom – displays the legend at the bottom of the chart.
  • msoElementLegendTop – displays the legend at the top of the chart.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Adding Data Labels Using VBA

We have a chart selected in the worksheet, as shown below:

Pie Chart without Labels

You can add data labels using the Chart.SetElement method. The following code adds data labels to the inside end of the chart:

Sub AddingADataLabels()

ActiveChart.SetElement msoElementDataLabelInsideEnd

End Sub

The result is:

Adding data labels to a Pie Chart in VBA

You can specify how the data labels are positioned in the following ways:

  • msoElementDataLabelShow – display data labels.
  • msoElementDataLabelRight – displays data labels on the right of the chart.
  • msoElementDataLabelLeft – displays data labels on the left of the chart.
  • msoElementDataLabelTop – displays data labels at the top of the chart.
  • msoElementDataLabelBestFit – determines the best fit.
  • msoElementDataLabelBottom – displays data labels at the bottom of the chart.
  • msoElementDataLabelCallout – displays data labels as a callout.
  • msoElementDataLabelCenter – displays data labels on the center.
  • msoElementDataLabelInsideBase – displays data labels on the inside base.
  • msoElementDataLabelOutSideEnd – displays data labels on the outside end of the chart.
  • msoElementDataLabelInsideEnd – displays data labels on the inside end of the chart.

Adding an X-axis and Title in VBA

We have a chart selected in the worksheet, as shown below:

Column Chart

You can add an X-axis and X-axis title using the Chart.SetElement method. The following code adds an X-axis and X-axis title to the chart:

Sub AddingAnXAxisandXTitle()

With ActiveChart
.SetElement msoElementPrimaryCategoryAxisShow
.SetElement msoElementPrimaryCategoryAxisTitleHorizontal
End With


End Sub

The result is:

Adding an X-axis and Axis Title Using VBA

Adding a Y-axis and Title in VBA

We have a chart selected in the worksheet, as shown below:

Chart for Y-axis and title

You can add a Y-axis and Y-axis title using the Chart.SetElement method. The following code adds an Y-axis and Y-axis title to the chart:

Sub AddingAYAxisandYTitle()

With ActiveChart
.SetElement msoElementPrimaryValueAxisShow
.SetElement msoElementPrimaryValueAxisTitleHorizontal
End With
End Sub

The result is:

Adding a Y-Axis and Axis Title Using VBA

VBA Programming | Code Generator does work for you!

Changing the Number Format of An Axis

We have a chart selected in the worksheet, as shown below:

Chart Selected For Changing The Number Format

You can change the number format of an axis. The following code changes the number format of the y-axis to currency:

Sub ChangingTheNumberFormat()

ActiveChart.Axes(xlValue).TickLabels.NumberFormat = "$#,##0.00"

End Sub

The result is:

Changing the Number Format of an Axis Using VBA

Changing the Formatting of the Font in a Chart

We have the following chart selected in the worksheet as shown below:

Source Chart For Formatting in VBA

You can change the formatting of the entire chart font, by referring to the font object and changing its name, font weight, and size. The following code changes the type, weight and size of the font of the entire chart.

Sub ChangingTheFontFormatting()

With ActiveChart


.ChartArea.Format.TextFrame2.TextRange.Font.Name = "Times New Roman"
.ChartArea.Format.TextFrame2.TextRange.Font.Bold = True
.ChartArea.Format.TextFrame2.TextRange.Font.Size = 14

End With

The result is:

Changing The Format of the Font of the Entire Chart in VBA

Deleting a Chart Using VBA

We have a chart selected in the worksheet, as shown below:

Chart Source For Delete

We can use the following code in order to delete this chart:

Sub DeletingTheChart()

ActiveChart.Parent.Delete

End Sub

Referring to the ChartObjects Collection

You can access all the embedded charts in your worksheet or workbook by referring to the ChartObjects collection. We have two charts on the same sheet shown below:

Chart Source For Chart Objects

We will refer to the ChartObjects collection in order to give both charts on the worksheet the same height, width, delete the gridlines, make the background color the same, give the charts the same plot area color and make the plot area line color the same color:

Sub ReferringToAllTheChartsOnASheet()

Dim cht As ChartObject

For Each cht In ActiveSheet.ChartObjects
cht.Height = 144.85
cht.Width = 246.61

cht.Chart.Axes(xlValue).MajorGridlines.Delete
cht.Chart.PlotArea.Format.Fill.ForeColor.RGB = RGB(242, 242, 242)
cht.Chart.ChartArea.Format.Fill.ForeColor.RGB = RGB(234, 234, 234)
cht.Chart.PlotArea.Format.Line.ForeColor.RGB = RGB(18, 97, 172)

Next cht

End Sub

The result is:

VBA ChartObjects Collection

Inserting a Chart on Its Own Chart Sheet

We have the range A1:B6 which contains the source data, shown below:

Source Range For Chart Sheet

You can create a chart using the Charts.Add method. The following code will create a chart on its own chart sheet:

Sub InsertingAChartOnItsOwnChartSheet()

Sheets("Sheet1").Range("A1:B6").Select
Charts.Add

End Sub

The result is:
Adding a Chart to Its Own Chart Sheet Using VBA

See some of our other charting tutorials:

Charts in Excel

Create a Bar Chart in VBA

Excel VBA Charts

We can term charts as objects in VBA. Similar to the worksheet, we can also insert charts in VBA. First, we select the data and chart type we want for our data. Now, there are two different types of charts we provide. One is the embed chart, where the chart is in the same sheet of data. Another is known as the chart sheet, where the chart is in a separate data sheet.

In data analysis, visual effects are the key performance indicators of the person who has done the analysis. Visuals are the best way an analyst can convey their message. Since we are all Excel users, we usually spend considerable time analyzing the data and drawing conclusions with numbers and charts. Creating a chart is an art to master. We hope you have good knowledge of creating charts with excelIn Excel, a graph or chart lets us visualize information we’ve gathered from our data. It allows us to visualize data in easy-to-understand pictorial ways. The following components are required to create charts or graphs in Excel: 1 — Numerical Data, 2 — Data Headings, and 3 — Data in Proper Order.read more. This article will show you how to create charts using VBA coding.

Table of contents
  • Excel VBA Charts
    • How to Add Charts using VBA Code in Excel?
      • #1 – Create Chart using VBA Coding
      • #2 – Create a Chart with the Same Excel Sheet as Shape
      • #3 – Code to Loop through the Charts
      • #4 – Alternative Method to Create Chart
    • Recommended Articles

VBA Charts

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Charts (wallstreetmojo.com)

How to Add Charts using VBA Code in Excel?

You can download this VBA Charts Excel Template here – VBA Charts Excel Template

#1 – Create Chart using VBA Coding

To create any chart, we should have some numerical data. For this example, we are going to use the below sample data.

VBA Chart Example 1

First, let us jump to the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more.

Step 1: Start Sub Procedure.

Code:

Sub Charts_Example1()

End Sub

VBA Chart Example 1-1

Step 2: Define the variable as Chart.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart

End Sub

VBA Chart Example 1-2

Step 3: Since the chart is an object variable, we need to Set it.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

End Sub

VBA Chart Example 1-3

The above code will add a new sheet as a chart sheet, not a worksheet.

VBA Chart Example 1-4

Step 4: Now, we need to design the chart. Open With Statement.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

  With MyChart

  End With

End Sub

VBA Chart Example 1-5

Step 5: The first thing we need to do with the chart is to Set the source range by selecting the “Set Source Data” method.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

  With MyChart
  .SetSourceData

  End With

End Sub

VBA Chart Example 1-6

Step 6: We need to mention the source range. In this case, my source range is in the sheet named “Sheet1,” and the range is “A1 to B7”.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

  With MyChart
  .SetSourceData Sheets("Sheet1").Range("A1:B7")
  End With

End Sub

Example 1-7

Step 7: Next up, we need to select the kind of chart we are going to create. For this, we need to select the Chart Type property.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

  With MyChart
  .SetSourceData Sheets("Sheet1").Range("A1:B7")
  .ChartType =
  End With

End Sub

VBA Chart Example 1-8

Step 8: Here, we have a variety of charts. I am going to select the “xlColumnClustered” chart.

Code:

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

  With MyChart
  .SetSourceData Sheets("Sheet1").Range("A1:B7")
  .ChartType = xlColumnClustered
  End With

End Sub

Example 1-9

Now let’s run the code using the F5 key or manually and see how the chart looks.

VBA Chart Example 1-10

Step 9: Now, change other properties of the chart. To change the chart title, below is the code.

Example 1-11

Like this, we have many properties and methods with charts. Use each one of them to see the impact and learn.

Sub Charts_Example1()

  Dim MyChart As Chart
  Set MyChart = Charts.Add

  With MyChart
  .SetSourceData Sheets("Sheet1").Range("A1:B7")
  .ChartType = xlColumnClustered
  .ChartTitle.Text = "Sales Performance"
  End With

End Sub

#2 – Create a Chart with the Same Excel Sheet as Shape

We need to use a different technique to create the chart with the same worksheet (datasheet) as the shape.

Step 1: First, declare three object variables.

Code:

Sub Charts_Example2()

  Dim Ws As Worksheet
  Dim Rng As Range
  Dim MyChart As Object

End Sub

VBA Chart Example 2

Step 2: Then, set the worksheet reference.

Code:

Sub Charts_Example2()

  Dim Ws As Worksheet
  Dim Rng As Range
  Dim MyChart As Object

  Set Ws = Worksheets("Sheet1")

End Sub

Example 2-1

Step 3: Now, set the range object in VBARange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more

Code:

Sub Charts_Example2()

  Dim Ws As Worksheet
  Dim Rng As Range
  Dim MyChart As Object

  Set Ws = Worksheets("Sheet1")
  Set Rng = Ws.Range("A1:B7")

End Sub

Example 2-2

Step 4: Now, set the chart object.

Code:

Sub Charts_Example2()

  Dim Ws As Worksheet
  Dim Rng As Range
  Dim MyChart As Object

  Set Ws = Worksheets("Sheet1")
  Set Rng = Ws.Range("A1:B7")
  Set MyChart = Ws.Shapes.AddChart2

End Sub

Example 2-3

Step 5: Now, as usual, we can design the chart using the “With” statement.

VBA Chart Example 2-4

Code:

Sub Charts_Example2()

Dim Ws As Worksheet 'To Hold Worksheet Reference
Dim Rng As Range 'To Hold Range Reference in the Worksheet
Dim MyChart As Object

Set Ws = Worksheets("Sheet1") 'Now variable "Ws" is equal to the sheet "Sheet1"
Set Rng = Ws.Range("A1:B7") 'Now variable "Rng" holds the range A1 to B7 in the sheet "Sheet1"
Set MyChart = Ws.Shapes.AddChart2 'Chart will be added as Shape in the same worksheet

With MyChart.Chart
.SetSourceData Rng 'Since we already set the range of cells to be used for chart we have use RNG object here
.ChartType = xlColumnClustered
.ChartTitle.Text = "Sales Performance"
End With

End Sub

It will add the chart below.

VBA Chart Example 2-5

#3 – Code to Loop through the Charts

Like how we look through sheets to change the name, insert values, and hide and unhide them. Similarly, we need to use the ChartObject property to loop through the charts.

The below code will loop through all the charts in the worksheet.

Code:

Sub Chart_Loop()

  Dim MyChart As ChartObject
 
  For Each MyChart In ActiveSheet.ChartObjects
  'Enter the code here
  Next MyChart

End Sub

#4 – Alternative Method to Create Chart

We can use the below alternative method to create charts. We can use the ChartObject. Add method to create the chart below is the example code.

It will also create a chart like the previous method.

Code:

Sub Charts_Example3()

  Dim Ws As Worksheet
  Dim Rng As Range
  Dim MyChart As ChartObject

  Set Ws = Worksheets("Sheet1")
  Set Rng = Ws.Range("A1:B7")
  Set MyChart = Ws.ChartObjects.Add(Left:=ActiveCell.Left, Width:=400, Top:=ActiveCell.Top, Height:=200)
  MyChart.Chart.SetSourceData Source:=Rng
  MyChart.Chart.ChartType = xlColumnStacked
  MyChart.Chart.ChartTitle.Text = "Sales Performance"

End Sub

Recommended Articles

This article has been a guide to VBA Charts. Here, we learn how to create a chart using VBA code, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –

  • Excel VBA Pivot Table
  • What are Control Charts in Excel?
  • Top 8 Types of Charts in Excel
  • Graphs vs. Charts – Compare

VBA Coding Guide To Charts & Graphs For Microsoft Excel

Charts, Charts, & More Charts!

Graphical visualizations are arguably the pinnacle of how an analyst shares his/her results and possessing the ability to manipulate them is key to the field.  Since we as data analysts spend some much time creating graphs, it is more valuable than ever to understand how to automate them.

What if you have 20 graphs on a spreadsheet and they all need to have their legends in the exact same spot?  What if you create a bunch of charts and your manager needs the series colors changed at the last minute? Do you want to do this all manually?

Below will be your cheat sheet for manipulating Excel charts & graphs with VBA code.  Please let me know via the comments section if there are areas missing from this guide so I can expand on them.  Enjoy!

VBA Chart Guide Contents

  • Create/Insert Chart

  • Looping Through Charts/Series

  • Chart Title (Adding/Modifying)

  • Chart Legend (Adding/Modifying)

  • Adding Various Chart Attributes

  • Modifying Various Chart Attributes

  • Removing Various Chart Attributes

  • Change Chart Colors

  • Chart Excel Add-ins

Inserting A Chart

Method 1:

Sub CreateChart()
‘PURPOSE: Create a chart (chart dimensions are not required)

Dim rng As Range
Dim cht As Object

‘Your data range for the chart
  Set rng = ActiveSheet.Range(«A24:M27»)

‘Create a chart
  Set cht = ActiveSheet.Shapes.AddChart2

‘Give chart some data
  cht.Chart.SetSourceData Source:=rng

‘Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines

End Sub

Sub CreateChart()
‘PURPOSE: Create a chart (chart dimensions are required)

Dim rng As Range
Dim cht As ChartObject

‘Your data range for the chart
  Set rng = ActiveSheet.Range(«A24:M27»)

‘Create a chart
  Set cht = ActiveSheet.ChartObjects.Add( _
    Left:=ActiveCell.Left, _
    Width:=450, _
    Top:=ActiveCell.Top, _
    Height:=250)

‘Give chart some data
  cht.Chart.SetSourceData Source:=rng

‘Determine the chart type
  cht.Chart.ChartType = xlXYScatterLines

       End Sub

Looping Through Charts & Series

Sub LoopThroughCharts()
‘PURPOSE: How to cycle through charts and chart series

Dim cht As ChartObject
Dim ser As Series

‘Loop Through all charts on ActiveSheet
  For Each cht In ActiveSheet.ChartObjects

  Next cht

‘Loop through all series in a chart
  For Each ser In grph.Chart.SeriesCollection

  Next ser

  ‘Loop Through all series on Activesheet
  For Each cht In ActiveSheet.ChartObjects
    For Each ser In grph.Chart.SeriesCollection

    Next ser
  Next cht

  End Sub

Adding & Modifying A Chart Title

Add Chart Title

Sub AddChartTitle()
‘PURPOSE: Add a title to a specific chart

Dim cht As ChartObject

Set cht = ActiveSheet.ChartObjects(«Chart 1»)

‘Ensure chart has a title
  cht.Chart.HasTitle = True

‘Change chart’s title
  cht.Chart.ChartTitle.Text = «My Graph»

End Sub

Move/Reposition Chart Title

Sub RepositionChartTitle()
‘PURPOSE: Reposition a chart’s title

Dim cht As ChartObject

Set cht = ActiveSheet.ChartObjects(«Chart 1»)

‘Reposition title
  With cht.Chart.ChartTitle
    .Left = 100
    .Top = 50
  End With

End Sub

Adding & Modifying A Graph Legend

Insert/Create Chart Legend

Sub InsertChartLegend()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects(«Chart 1»).Chart

‘Add Legend to the Right
  cht.SetElement (msoElementLegendRight)

  ‘Add Legend to the Left
  cht.SetElement (msoElementLegendLeft)

  ‘Add Legend to the Bottom
  cht.SetElement (msoElementLegendBottom)

  ‘Add Legend to the Top
  cht.SetElement (msoElementLegendTop)

  ‘Add Overlaying Legend to the Left
  cht.SetElement (msoElementLegendLeftOverlay)

  ‘Add Overlaying Legend to the Right
  cht.SetElement (msoElementLegendRightOverlay)

End Sub

Resize/Move Chart Legend

Sub DimensionChartLegend()

Dim lgd As Legend

Set lgd = ActiveSheet.ChartObjects(«Chart 1»).Chart.Legend

lgd.Left = 240.23
lgd.Top = 6.962
lgd.Width = 103.769
lgd.Height = 25.165

End Sub

Adding Various Chart Attributes

Sub AddStuffToChart()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects(«Chart 1»).Chart

‘Add X-axis
  cht.HasAxis(xlCategory, xlPrimary) = True ‘[Method #1]
  cht.SetElement (msoElementPrimaryCategoryAxisShow) ‘[Method #2]

  ‘Add X-axis title
  cht.Axes(xlCategory, xlPrimary).HasTitle = True ‘[Method #1]
  cht.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) ‘[Method #2]

  ‘Add y-axis
  cht.HasAxis(xlValue, xlPrimary) = True ‘[Method #1]
  cht.SetElement (msoElementPrimaryValueAxisShow) ‘[Method #2]

  ‘Add y-axis title
  cht.Axes(xlValue, xlPrimary).HasTitle = True ‘[Method #1]
  cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis) ‘[Method #2]

  ‘Add Data Labels (Centered)
  cht.SetElement (msoElementDataLabelCenter)

‘Add Major Gridlines
  cht.SetElement (msoElementPrimaryValueGridLinesMajor)

    ‘Add Linear Trend Line
  cht.SeriesCollection(1).Trendlines.Add Type:=xlLinear

  End Sub

Modifying Various Chart Attributes

Sub ChangeChartFormatting()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects(«Chart 1»).Chart

‘Adjust y-axis Scale
  cht.Axes(xlValue).MinimumScale = 40
  cht.Axes(xlValue).MaximumScale = 100

‘Adjust x-axis Scale
  cht.Axes(xlCategory).MinimumScale = 1
  cht.Axes(xlCategory).MaximumScale = 10

  ‘Adjust Bar Gap
  cht.ChartGroups(1).GapWidth = 60

‘Format Font Size
  cht.ChartArea.Format.TextFrame2.TextRange.Font.Size = 12

  ‘Format Font Type
  cht.ChartArea.Format.TextFrame2.TextRange.Font.Name = «Arial»

  ‘Make Font Bold
  cht.ChartArea.Format.TextFrame2.TextRange.Font.Bold = msoTrue

  ‘Make Font Italicized
  cht.ChartArea.Format.TextFrame2.TextRange.Font.Italic = msoTrue

End Sub

Removing Various Chart Attributes

Sub RemoveChartFormatting()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects(«Chart 1»).Chart

‘Remove Chart Series
  cht.SeriesCollection(2).Delete

‘Remove Gridlines
  cht.Axes(xlValue).MajorGridlines.Delete
  cht.Axes(xlValue).MinorGridlines.Delete

  ‘Remove X-axis
  cht.Axes(xlCategory).Delete

‘Remove Y-axis
  cht.Axes(xlValue).Delete

‘Remove Legend
  cht.Legend.Delete

‘Remove Title
  cht.ChartTitle.Delete

    ‘Remove ChartArea border
  cht.ChartArea.Border.LineStyle = xlNone

‘No background color fill
  cht.ChartArea.Format.Fill.Visible = msoFalse
  cht.PlotArea.Format.Fill.Visible = msoFalse

End Sub

Change Chart Colors

Sub ChangeChartColors()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects(«Chart 1»).Chart

‘Change first bar chart series fill color
  cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(91, 155, 213)

‘Change X-axis label color
  cht.Axes(xlCategory).TickLabels.Font.Color = RGB(91, 155, 213)

‘Change Y-axis label color
  cht.Axes(xlValue).TickLabels.Font.Color = RGB(91, 155, 213)

  ‘Change Plot Area border color
  cht.PlotArea.Format.Line.ForeColor.RGB = RGB(91, 155, 213)

  ‘Change Major gridline color
  cht.Axes(xlValue).MajorGridlines.Format.Line.ForeColor.RGB = RGB(91, 155, 213)

‘Change Chart Title font color
  cht.ChartTitle.Format.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(91, 155, 213)

‘No background color fill
  cht.ChartArea.Format.Fill.Visible = msoFalse
  cht.PlotArea.Format.Fill.Visible = msoFalse

End Sub

Chart Excel Add-ins

  • Waterfall Chart Excel Add-in — Automatically create editable Waterfall Charts directly in your spreadsheet.

  • AutoChart Excel Add-in — This add-in will allow you to create, manipulate series ranges, and format all your charts at once. Making adjustments has never been easier!

  • myBrand Excel Add-in — Stores your favorite colors to the Excel Ribbon and allows you to color cells, shapes, and charts.

  • Peltier Tech Charts for Excel — A chart-building toolkit with the automated creation of difficult chart builds such as Histograms, Pareto, Marimekko, and many more.

Anything You Would Like To See?

There are a ton of things you can do with VBA and Excel charts.  I attempted through this guide to tackle the most general ones, but please don’t hesitate to leave a comment if there is something that you would like to see added to the code in this VBA guide.  Hopefully, you were able to find what you were looking for!

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

How to add, edit, and position charts in Excel using VBA.

This tutorial covers what to do when adding the chart.

b50b63d27ee63c7c9c4688e821b4ab02.png

Sections:

Add a Chart with VBA/Macros

Set Chart Source Data

Set Chart Type

Change Chart Title

Set Category and Value Titles

Include a Legend

Change Chart Size and Position

Fewer Arguments

Notes

Add a Chart with VBA/Macros

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

This is the basic code for adding a chart to a worksheet using a macro. Each section of code in the macro has a comment that explains what that section does, also, each section below here explains how to change and use the macro in more detail.

Set Chart Source Data

This tells the chart what data to use.

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

Source:=Worksheets(«Sheet1»).Range(«A1:E4») this holds the range reference for the chart.

Worksheets(«Sheet1»).Range(«A1:E4») is the range reference.

Make sure to specify from which worksheet you want to get the source data, otherwise, it will come from the currently active or visible worksheet.

Possible Values

Any range from any worksheet, including named ranges.

Set Chart Type

This controls the type of chart to use.

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

Gallery:=xlLine the name of this argument is Gallery, which can seem confusing, but it just controls the type of chart that will be used to display your source data. xlLine is the type of chart that will be used — you can view a full list of possible chart types below here.

List of Possible Chart Types:

Name Value Description
xl3DArea -4098 3D Area.
xl3DAreaStacked 78 3D Stacked Area.
xl3DAreaStacked100 79 100% Stacked Area.
xl3DBarClustered 60 3D Clustered Bar.
xl3DBarStacked 61 3D Stacked Bar.
xl3DBarStacked100 62 3D 100% Stacked Bar.
xl3DColumn -4100 3D Column.
xl3DColumnClustered 54 3D Clustered Column.
xl3DColumnStacked 55 3D Stacked Column.
xl3DColumnStacked100 56 3D 100% Stacked Column.
xl3DLine -4101 3D Line.
xl3DPie -4102 3D Pie.
xl3DPieExploded 70 Exploded 3D Pie.
xlArea 1 Area
xlAreaStacked 76 Stacked Area.
xlAreaStacked100 77 100% Stacked Area.
xlBarClustered 57 Clustered Bar.
xlBarOfPie 71 Bar of Pie.
xlBarStacked 58 Stacked Bar.
xlBarStacked100 59 100% Stacked Bar.
xlBubble 15 Bubble.
xlBubble3DEffect 87 Bubble with 3D effects.
xlColumnClustered 51 Clustered Column.
xlColumnStacked 52 Stacked Column.
xlColumnStacked100 53 100% Stacked Column.
xlConeBarClustered 102 Clustered Cone Bar.
xlConeBarStacked 103 Stacked Cone Bar.
xlConeBarStacked100 104 100% Stacked Cone Bar.
xlConeCol 105 3D Cone Column.
xlConeColClustered 99 Clustered Cone Column.
xlConeColStacked 100 Stacked Cone Column.
xlConeColStacked100 101 100% Stacked Cone Column.
xlCylinderBarClustered 95 Clustered Cylinder Bar.
xlCylinderBarStacked 96 Stacked Cylinder Bar.
xlCylinderBarStacked100 97 100% Stacked Cylinder Bar.
xlCylinderCol 98 3D Cylinder Column.
xlCylinderColClustered 92 Clustered Cone Column.
xlCylinderColStacked 93 Stacked Cone Column.
xlCylinderColStacked100 94 100% Stacked Cylinder Column.
xlDoughnut -4120 Doughnut.
xlDoughnutExploded 80 Exploded Doughnut.
xlLine 4 Line.
xlLineMarkers 65 Line with Markers.
xlLineMarkersStacked 66 Stacked Line with Markers.
xlLineMarkersStacked100 67 100% Stacked Line with Markers.
xlLineStacked 63 Stacked Line.
xlLineStacked100 64 100% Stacked Line.
xlPie 5 Pie.
xlPieExploded 69 Exploded Pie.
xlPieOfPie 68 Pie of Pie.
xlPyramidBarClustered 109 Clustered Pyramid Bar.
xlPyramidBarStacked 110 Stacked Pyramid Bar.
xlPyramidBarStacked100 111 100% Stacked Pyramid Bar.
xlPyramidCol 112 3D Pyramid Column.
xlPyramidColClustered 106 Clustered Pyramid Column.
xlPyramidColStacked 107 Stacked Pyramid Column.
xlPyramidColStacked100 108 100% Stacked Pyramid Column.
xlRadar -4151 Radar.
xlRadarFilled 82 Filled Radar.
xlRadarMarkers 81 Radar with Data Markers.
xlStockHLC 88 High-Low-Close.
xlStockOHLC 89 Open-High-Low-Close.
xlStockVHLC 90 Volume-High-Low-Close.
xlStockVOHLC 91 Volume-Open-High-Low-Close.
xlSurface 83 3D Surface.
xlSurfaceTopView 85 Surface (Top View).
xlSurfaceTopViewWireframe 86 Surface (Top View wireframe).
xlSurfaceWireframe 84 3D Surface (wireframe).
xlXYScatter -4169 Scatter.
xlXYScatterLines 74 Scatter with Lines.
xlXYScatterLinesNoMarkers 75 Scatter with Lines and No Data Markers.
xlXYScatterSmooth 72 Scatter with Smoothed Lines.
xlXYScatterSmoothNoMarkers 73 Scatter with Smoothed Lines and No Data Markers.

Change Chart Title

Title of the chart.

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

Title:=»Chart Title» put whatever you want inside of the quotation marks for the title of the chart.

Set Category and Value Titles

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

CategoryTitle:=»Category Title» the title that goes along the bottom of the chart. Put whatever you want within the quotation marks.

ValueTitle:=»Value Title» the title that goes along the left side of the chart. Put whatever you want within the quotation marks.

Include a Legend

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

HasLegend:=True when this is set to True, a legend will appear — also, often times a legend will appear by default. If you want to make sure there is no legend, set this value to False.

Possible Values

True show a legend.

False don’t show a legend.

Sometimes legends appear by default; use False when you want to ensure that none will appear.

Change Chart Size and Position

Sub CreateChart()

'Tell the macro to make a variable that can hold the chart.
Dim myChart As ChartObject

'Create a chart and put the newly created chart inside of the variable created above.
Set myChart = Worksheets("sheet1").ChartObjects.Add(10, 80, 300, 175)

'Add some basic elements to the chart
myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

End Sub

ChartObjects.Add(10, 80, 300, 175) the numbers here control the size and position of the chart.

Add(Left, Top, Width, Height)

10 is the position from the left side of the worksheet. You can set this number to whatever you want so that the chart fits into your data nicely.

80 is the position from the top of the worksheet. You can set this number to whatever you want so that the chart fits into your data nicely.

300 is the width of the chart.

175 is the height of the chart.

Play around with these values until you get the desired size and position of the chart in your worksheet. Note that adding a legend to a chart will make it seem smaller as there will be less space for the data to be displayed.

Fewer Arguments

The above example includes a kind of ‘interesting’ way of writing the arguments for a function in VBA.

myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title", _
    HasLegend:=True

Each argument for the ChartWizard is put onto its own line and follows this format:

Source:= each line begins with the name of the argument and a :=

, _ each line ends with a comma and an underscore.

Last line this is important! The last line for the ChartWizard, should not end with , _ Notice that the last line is this: HasLegend:=True but if you did not want to include the HasLegend argument and wanted it to end with the ValueTitle argument, you would delete the HasLegend argument (entire line) and remove the , _ from the Value Title argument, like this:

myChart.Chart.ChartWizard _
    Source:=Worksheets("Sheet1").Range("A1:E4"), _
    Gallery:=xlLine, _
    Title:="Chart Title", _
    CategoryTitle:="Category Title", _
    ValueTitle:="Value Title"

This may seem confusing at first, but it’s standard practice in VBA and Macros.

Notes

There are many ways to add charts to Excel, especially considering new and old versions of the program; however, the example above provides a robust solution that will work across many versions of Excel.

Download the sample file to see the above examples in Excel.

Skip to content

Excel Chart VBA Examples and Tutorials

  • 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.

Excel Chart VBA Examples and Tutorials – Learning Path

  • Example tutorials on Creating Charts using Excel VBA:
  • Example tutorials on Chart Type using Excel VBA:
  • Example Tutorials on Formatting Chart Objects using Excel VBA:
  • Example Tutorials on Chart Collection in Excel VBA:
  • Other useful Examples and tutorials on Excel VBA Charting:
  • Excel VBA Charting Constants and Enumerations:
  • Example File for Free Download:

Creating Charts using Excel VBA

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 Sapes.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").Select
ActiveSheet.Shapes.AddChart.Select
End Sub

2. 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").Select
Charts.Add
End Sub

3. 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").Select
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"

End Sub

4. 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 With
End Sub

6. 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 Object
Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")
End Sub

7. 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 Object
Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")
cht.Left = 350
cht.Width = 400
cht.Top = 30
cht.Height = 200
End Sub

8. 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 Align

With ActiveSheet.ChartObjects(1)
.Left = Range("A6").Left
.Top = Range("A7").Top
.Width = Range("D6").Left
.Height = Range("D16").Top - Range("D6").Top
End With

End Sub

9. 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 Object
Set 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 = 200
End With
End Sub

10. 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).Activate
With ActiveChart
.SetSourceData Source:=Sheets("Temp").Range("C5:D7")
.Parent.Left = 350
.Parent.Width = 400
.Parent.Top = 30
.Parent.Height = 200
End With
End Sub

Top

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. Please check here list of enumerations available for Excel VBA Charting

Sub Ex_ChartType_Enumeration()
Dim cht As Object
Set 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 chart
End With
End Sub

12. 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. Please check here for list of enumerations available in Excel VBA Charting

Sub Ex_ChartType_xlConstant()
Dim cht As Object
Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
With cht
.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")
.Chart.Type = xlArea
End With
End Sub

xlConstants 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. Please check here for list of enumerations available in Excel VBA Charting

Sub Ex_ChartType_Pie_Chart()
Dim cht As Object
Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
With cht
.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")
.Chart.Type = xlPie
End With
End Sub

14. 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. Please check here for list of enumerations available in Excel VBA Charting

Sub Ex_ChartType_Line_Chart()
Dim cht As Object
Set 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
End With
End Sub

15. 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. Please check here for list of enumerations available in Excel VBA Charting

Sub Ex_ChartType_Bar_Chart()
Dim cht As Object
Set 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
End With
End Sub

16. Example to set the chart type as a XYScatter Chart in Excel VBA

The following code using xlXYScatter constant to plot the Pie chart. Please check here for list of enumerations available in Excel VBA Charting

Sub Ex_ChartType_XYScatter_Chart()
Dim cht As Object
Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300)
With cht
.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7")
.Chart.Type = xlXYScatter
End With
End Sub

Here is the complete list of Excel Chart Types, Chart Enumerations and Chart Constants:

Top

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 Object
Set 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 = 3
End With
End Sub

18. 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 Object
Set 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 = 5
End With
End Sub

19.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 Object
Set 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 = 5

End With
End Sub

20. 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 Object
Set 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 = 7
End With
End Sub

21. 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 Object
Set 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 = xlDash
End With
End Sub

22. 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 Object
Set 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 = 3
End With
End Sub

23. 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 Object
Set 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 With
End Sub

24. 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 Object
Set 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 With
End Sub

25. 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 Object
Set 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 = 2
End With
End Sub

Top

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 Object
For Each cht In ActiveSheet.ChartObjects
cht.Width = 400
cht.Height = 200
Next

End Sub

27. 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 Object
For Each cht In ActiveSheet.ChartObjects
cht.Delete
Next

End Sub

Top

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 chart
ActiveSheet.Shapes.AddChart.Select
With ActiveChart
'Specify source data and orientation
.SetSourceData Source:=Sheet1.Range("A1:C5")
End With

End Sub

29. 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 chart
ActiveSheet.Shapes.AddChart.Select
With ActiveChart
'Specify source data and orientation
.SetSourceData Source:=Sheets("Temp").Range("C5:D7"), PlotBy:=xlRows ' you can use xlColumns to swith it
End With

End Sub

30. 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 chart
ActiveSheet.Shapes.AddChart.Select
With 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 With
End Sub

31. 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).activate
ActiveChart.Axes(xlCategory).HasTitle = True
ActiveChart.Axes(xlCategory).AxisTitle.Text = "Quarter"

ActiveChart.Axes(xlValue).HasTitle = True
ActiveChart.Axes(xlValue).AxisTitle.Text = "Sales"

End Sub

32. 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).Activate
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "Overal Summary"

End Sub

33. Send an Excel Chart to an Outlook email using VBA

Download Example File:
ANALYSIS TABS – SendExcelChartToOutLook.xlsm

Following is the code to Send an Excel Chart to an Outlook email using VBA.

Sub SendChartThroughMail()
'Add refernce to Microsoft Outlook object Library

Dim olMail As MailItem
Dim objOL As Object
Dim sImgPath As String

Dim sHi As String
Dim sBody As String
Dim sThanks As String

' Saving chart as image
sImgPath = ThisWorkbook.Path & "Temp_" & Format(Now(), "DD_MM_YY_HH_MM_SS") & ".bmp"
Sheets("Sheet1").ChartObjects(1).Chart.Export sImgPath

'creating html body with image
sHi = "<font size='3' color='black'>" & "Hi," & "<br> <br>" & "Here is the required solution: " & "<br> <br> </font>"

sBody = "<p align='Left'><img src=""cid:" & Mid(sImgPath, InStrRev(sImgPath, "") + 1) & """ width=400 height=300 > <br> <br>"

sThanks = "<font size='3'>" & "Many thanks - ANALYSISTABS.COM <br>The Complete Reference For Analyst <br> website:<A HREF=""https://www.analysistabs.com""> analysistabs.com</A>" & "<br> <br> </font>"

'sending the email

Set objOL = CreateObject("Outlook.Application")
Set olMail = objOL.CreateItem(olMailItem)

With olMail
.To = "youremail@orgdomain.com"
.Subject = "ANALYSISTABS.COM: Test Mail with chart"
.Attachments.Add sImgPath
.HTMLBody = sHi & sBody & sThanks
.Display
End With

'Delete the saved chart
Kill sImgPath

'Free-up the objects
Set olMail = Nothing
Set olApp = Nothing

End Sub

Top

Excel VBA Chart Constants and Enumerations

Chart Types, Constants and Enumerations

CHART TYPE VBA CONSTANT VALUE

AREA Charts

AREA xlArea 1
STACKED AREA xlAreaStacked 76
100% STACKED AREA xlAreaStacked100 77
3D AREA xl3DArea -4098
3D STACKED AREA xl3DAreaStacked 78
3D 100% STACKED AREA xl3DAreaStacked100 79

BAR Charts

3D CLUSTERED BAR xl3DBarClustered 60
3D STACKED BAR xl3DBarStacked 61
3D 100% STACKED BAR xl3DBarStacked100 62
CLUSTERED BAR xlBarClustered 57
STACKED BAR xlBarStacked 58
100% STACKED BAR xlBarStacked100 59
CLUSTERED CONE BAR xlConeBarClustered 102
STACKED CONE BAR xlConeBarStacked 103
100% STACKED CONE BAR xlConeBarStacked100 104
CLUSTERED CYLINDER BAR xlCylinderBarClustered 95
STACKED CYLINDER BAR xlCylinderBarStacked 96
100% STACKED CYLINDER BAR xlCylinderBarStacked100 97
CLUSTERED PYRAMID BAR xlPyramidBarClustered 109
STACKED PYRAMID BAR xlPyramidBarStacked 110
100% STACKED PYRAMID BAR xlPyramidBarStacked100 111
BUBBLE Charts    
3D BUBBLE, BUBBLE WITH 3D EFFECTS xlBubble3DEffect 87
BUBBLE xlBubble 15

COLUMN Charts

3D CLUSTERED COLUMN xl3DColumnClustered 54
3D COLUMN xl3DColumn -4100
3D CONE COLUMN xlConeCol 105
3D CYLINDER COLUMN xlCylinderCol 98
3D PYRAMID COLUMN xlPyramidCol 112
3D STACKED COLUMN xl3DColumnStacked 55
3D 100% STACKED COLUMN xl3DColumnStacked100 56
CLUSTERED COLUMN xlColumnClustered 51
STACKED COLUMN xlColumnStacked 52
100% STACKED COLUMN xlColumnStacked100 53
CLUSTERED CONE COLUMN xlConeColClustered 99
STACKED CONE COLUMN xlConeColStacked 100
100% STACKED CONE COLUMN xlConeColStacked100 101
CLUSTERED CYLINDER COLUMN xlCylinderColClustered 92
STACKED CYLINDER COLUMN xlCylinderColStacked 93
100% STACKED CYLINDER COLUMN xlCylinderColStacked100 94
CLUSTERED PYRAMID COLUMN xlPyramidColClustered 106
STACKED PYRAMID COLUMN xlPyramidColStacked 107
100% STACKED PYRAMID COLUMN xlPyramidColStacked100 108

DOUGHNUT Charts

DOUGHNUT xlDoughnut -4120
EXPLODED DOUGHNUT xlDoughnutExploded 80

LINE Charts

3D LINE xl3DLine -4101
LINE xlLine 4
LINE WITH MARKERS xlLineMarkers 65
STACKED LINE xlLineStacked 63
100% STACKED LINE xlLineStacked100 64
STACKED LINE WITH MARKERS xlLineMarkersStacked 66
100% STACKED LINE WITH MARKERS xlLineMarkersStacked100 67

PIE Charts

3D PIE xl3DPie -4102
3D EXPLODED PIE xl3DPieExploded 70
BAR OF PIE xlBarOfPie 71
EXPLODED PIE xlPieExploded 69
PIE xlPie 5
PIE OF PIE xlPieOfPie 68

RADAR Charts

RADAR xlRadar -4151
FILLED RADAR xlRadarFilled 82
RADAR WITH DATA MARKERS xlRadarMarkers 81

SCATTER Charts

SCATTER xlXYScatter -4169
SCATTER WITH LINES xlXYScatterLines 74
SCATTER WITH LINES AND NO DATA MARKERS xlXYScatterLinesNoMarkers 75
SCATTER WITH SMOOTH LINES xlXYScatterSmooth 72
SCATTER WITH SMOOTH LINES AND NO DATA MARKERS xlXYScatterSmoothNoMarkers 73

STOCK Charts

STOCK HLC (HIGH-LOW-CLOSE) xlStockHLC 88
STOCK OHLC (OPEN-HIGH-LOW-CLOSE) xlStockOHLC 89
STOCK VHLC (VOLUME-HIGH-LOW-CLOSE) xlStockVHLC 90
STOCK VOHLC (VOLUME-OPEN-HIGH-LOW-CLOSE) xlStockVOHLC 91

SURFACE Charts

3D SURFACE xlSurface 83
3D SURFACE WIREFRAME xlSurfaceWireframe 84
SURFACE TOP VIEW xlSurfaceTopView 85
SURFACE TOP VIEW WIREFRAME xlSurfaceTopViewWireframe 86

Marker Styles, Constants and Enumerations

Marker Styles Name Value
Automatic markers xlMarkerStyleAutomatic -4105
Circular markers xlMarkerStyleCircle 8
Long bar markers xlMarkerStyleDash -4115
Diamond-shaped markers xlMarkerStyleDiamond 2
Short bar markers xlMarkerStyleDot -4118
No markers xlMarkerStyleNone -4142
Picture markers xlMarkerStylePicture -4147
Square markers with a plus sign xlMarkerStylePlus 9
Square markers xlMarkerStyleSquare 1
Square markers with an asterisk xlMarkerStyleStar 5
Triangular markers xlMarkerStyleTriangle 3
Square markers with an X xlMarkerStyleX -4168

Line Styles, Constants and Enumerations

Line Style Value
xlContinuous 1
xlDash -4115
xlDashDot 4
xlDashDotDot 5
xlDot -4118
xlDouble -4119
xlLineStyleNone -4142
xlSlantDashDot 13

Example file to Download

You can download the example file and have a look into the working codes.
ANALYSISTABS- Chart VBA Examples

Reference:
MSDN

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • Excel Chart VBA Examples and Tutorials – Learning Path
    • Creating Charts using Excel VBA
      • 1. Adding New Chart for Selected Data using Sapes.AddChart Method in Excel VBA
      • 2. Adding New Chart for Selected Data using Charts.Add Method : Creating Chart Sheet in Excel VBA
      • 3. Adding New Chart for Selected Data using Charts.Add Method : In Existing Sheet using Excel VBA
      • 4. Difference between embedded Chart and Chart Sheet in Excel:
      • 5. Adding New Chart for Selected Data using ChartObjects.Add Method in Excel VBA
      • 6. Assigning Charts to an Object in Excel VBA
      • 7. Changing the Chart Position in Excel VBA
      • 8. Align Chart Object at a Particular Range or Cell in Excel VBA
      • 9. Use with statement while dealing with Charts and avoid the accessing the same object repeatedly in Excel VBA
      • 10. You can use ActiveChart Object to access the active chart in Excel VBA
    • Setting Chart Types using Excel VBA
      • 11. Example to Change Chart type using Excel Chart Enumerations in Excel VBA
      • 12. Example to Change Chart type using Excel Chart Constants in VBA
      • 13. Example to set the type as a Pie Chart in Excel VBA
      • 14. Example to set the chart type as a Line Chart in Excel VBA
      • 15. Example to set the chart type as a Bar Chart in Excel VBA
      • 16. Example to set the chart type as a XYScatter Chart in Excel VBA
    • Formatting Chart Objects using Excel VBA
      • 17. Changing Chart Background Color – Chart Aria Interior Color in Excel VBA
      • 18. Changing PlotAria Background Color – PlotAria Interior Color in Excel VBA
      • 19.Changing Chart Series Background Color – Series Interior Color in Excel VBA
      • 20. Changing Chart Series Marker Style in Excel VBA
      • 21. Changing Chart Series Line Style in Excel VBA
      • 22. Changing Chart Series Border Color in Excel VBA
      • 23. Change Chart Axis NumberFormat in Excel VBA
      • 24. Formatting Axis Labels: Changing Axis Font to Bold using Excel VBA
      • 25. Two Y-axes Left and Right of Charts(Primary Axis and Secondary Axis) using Excel VBA
    • Chart Collection in Excel VBA
      • 26. Set equal widths and heights for all charts available in a Worksheet using Excel VBA
      • 27. Delete All Charts in a Worksheet using Excel VBA
    • Other useful Examples and tutorials on Excel VBA Charting
      • 28. Set Chart Data Source using Excel VBA
      • 29. Swap or Switch Rows and Columns in Excel Charts using VBA
      • 30. Set Chart Data Labels and Legends using Excel VBA
      • 31. Changing Axis Titles of a Chart in Excel VBA
      • 32. Change Titles of a Chart using Excel VBA
      • 33. Send an Excel Chart to an Outlook email using VBA
    • Excel VBA Chart Constants and Enumerations
      • Chart Types, Constants and Enumerations
      • Marker Styles, Constants and Enumerations
      • Line Styles, Constants and Enumerations
    • Example file to Download

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

30 Comments

  1. Tim
    December 18, 2013 at 11:33 PM — Reply

    HI there PNRao,

    This is a really great reference – in the past, I’ve beat around the object browser as well. I use MS Graph in an MS Access application (currently A2007 in process of being upgraded from A2003). I have numerous controls to do some of the tasks you’ve identified here and others as well. I also have a button for the very few advanced users UI have to be able to actually open MS Graph in a separate window and do formatting there. What I’m trying to figure out how to do is enumerate through ALL properties of a chart and save them as an array or tab delimited string in a database (Oracle in this case) field.

    Is there anyway to do this? I’ve done lots of the sorts of enumeration that you show show excellently here. What I would very much like to do is to be able to enumerate all formatting properties of a chart to be able to store it (above) and retrieve.

    Do you have any ideas? Thanks in advance,

    Tim

  2. PNRao
    December 19, 2013 at 11:30 AM — Reply

    Hi Tim,
    It is good idea to store all properties as enumerations in a field and draw the charts based on the requirement. You can consider the following things to save in the data base.
    1. Chart Type
    2. Data Source
    3. Axes (Primary/Secondary)
    4. Border
    5. Number Format
    6. Legend Alignment
    7. Data Labels
    8. Chart title

    You can make all the above properties as dynamic and the other things like Colors and minimum and maximum axis should be automatic.

    And you can provide UI to format the charts using drop-down lists and Text boxes. For example, you can show different chart types in drop-down and chart type can be changed based on the user selection. You can provide text box to enter the chart title, it should save in your database for chart titles enumeration to reflect on your chart.

    Hope this helps, let me know if you need any help on this.

    Thanks
    PNRao!

  3. kamran
    February 28, 2014 at 3:44 PM — Reply

    One of the best Tutorial for VBA macro.

  4. Antoni
    April 23, 2014 at 9:02 PM — Reply

    Hi,

    My boss has asked me to do many graphics chars, i love the example and explanations that have left at this web, I would like to do what our friend says PNRao, please have you any example of how to do it?

    Thank you very much.
    Antoni.

  5. PNRao
    April 24, 2014 at 8:48 PM — Reply

    Hi Antoni,

    We can automate charting using VBA. We have provided some examples in download page. You can download and see the examples, let us know if you need any help.

    Thanks-PNRao!

  6. Antoni
    April 25, 2014 at 8:15 PM — Reply

    Hi PNRao,

    I can’t found examples in the Download section, can you help me please?, or can you send me a links?

    Thank you.

  7. PNRao
    April 26, 2014 at 12:08 AM — Reply

    Hi Antoni,
    I have added the example file at end of the post. Please download and see the code.

    Thanks-PNRao!

  8. Sam
    May 4, 2014 at 9:32 AM — Reply

    Hi,
    I am having a task, in which i need to copy chart from one excel sheet to another excel sheet.
    So can you please help me in this.
    Thanks,
    Sam

  9. PNRao
    May 4, 2014 at 11:40 AM — Reply

    Hi Sam,

    You can use the Copy method as shown below:
    [vb]
    Sub sbVBA_Chart_Copy()
    Sheet1.ChartObjects(«Chart 1»).Copy ‘Sheet name and Chart Object name to be copied
    Sheet2.Activate ‘Activate your destination Sheet
    Range(«G1»).Select ‘Select your destination cell
    ActiveSheet.Paste ‘Now Paste
    End Sub
    [/vb]

    Thanks-PNRao!

  10. Ross
    December 29, 2014 at 9:02 PM — Reply

    Hi PNRao,

    Thanks for the above it’s really helpful, although I’m still stuck!

    Is there a way to so that when making a graph it has a certain destination within the sheet so it’s not pasted over my data?

    Thank you!!

  11. เสื้อคู่
    May 25, 2015 at 3:43 PM — Reply

    Hi, this weekend is pleasant in favor of me, since this moment i am reading
    this great informative post here at my residence.

  12. Nkhoma Kenneth
    October 4, 2015 at 1:27 PM — Reply

    Thanks very much for the tutorial, it is a great one indeed and very helpful.

    Thanks to you, i have learn’t something.

  13. Richard
    December 1, 2015 at 4:59 PM — Reply

    Hi Guys
    Great info – Thanks

    I’m trying to automate some graph formatting, and whilst I’ve worked out how to change the range for a xlTimeScale based graph, I want an easy way for the user to define which graphs need to be scaled to current month rather than all year.

    I thought of putting a text string into the Alt Text Description box (found under / but how do I read that field from a macro?

    If it were a shape I could use something like shapeDesc = sheet(1).Shapes(1).AlternativeText but that doesn’t work for ChartObjects.

    Any ideas?
    Thanks
    Richard

    Always learning … :-)

  14. Richard
    December 1, 2015 at 7:44 PM — Reply

    Hah! Got it guys.
    I’ve decided to scroll through each sheet. In each sheet scroll through each Shape. If the Shape.Type = msoChart Then I can pick up the Alternative Text and act accordingly.

    Code extract:
    For lShtCtr = 1 To ThisWorkbook.Sheets.Count
    Debug.Print “Checking worksheet ” & lShtCtr & ” ” & Sheets(lShtCtr).Name & “. Detected ” & ThisWorkbook.Sheets(lShtCtr).Shapes.Count & ” shapes.”
    For lShapeCtr = 1 To ThisWorkbook.Sheets(lShtCtr).Shapes.Count
    If ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Type = msoChart Then
    myText = ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).AlternativeText
    Debug.Print “Alt Text in ” & ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Name & ” =:” & myText
    If InStr(1, myText, “#AutoScale”, vbTextCompare) > 0 Then
    Debug.Print “Scaling axes on ” & ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Name
    Call ScaleAxes(ThisWorkbook.Sheets(lShtCtr), ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Name)
    End If ‘myText contains #AutoScale
    End If ‘Shape.Type = msoChart
    Next lShapeCtr
    Next lShtCtr

    The debug.print allow you to see what is going on. I’ve used the magic key phrase ‘#AutoScale’ as my command

    Thanks
    Richard

    Always learning :-)

  15. Krishnaprasad Menon
    January 2, 2016 at 10:45 AM — Reply

    Very nice tutorial.. Chart creating example file is not available on download… Kindly make it available

  16. PNRao
    January 2, 2016 at 11:38 PM — Reply

    Thanks for your valuable feedback and reporting an issue, we have fixed it.

    Thanks-PNRao!

  17. HS
    March 19, 2016 at 5:12 PM — Reply

    Very quickly this site will be famous amid all blogging and site-building
    users, due to it’s good posts

  18. chris
    May 9, 2016 at 1:05 AM — Reply

    i want to explode on a pie chart the piece with the max value. How can i do this? Also what if I have on a pie two pieces with the same max value? Thank you.

  19. Nagaraju
    July 1, 2016 at 12:17 PM — Reply

    Hi All,

    I’m trying to open website through Vba code….It was done…I need small information that if need code how to search search any information in google and display.

    Regards,
    Nagu

  20. Salty
    August 25, 2016 at 11:12 PM — Reply

    Hi
    This comment relates to your Example 13, above, but may apply to all of the Chart.Type examples.
    Using Excel 2016 on Windows 8, I had to change one line as follows:
    From > Chart.Type = xlPie
    To > Chart.Chart.Type = xlPie

  21. Salty
    August 29, 2016 at 9:01 AM — Reply

    Hi
    Sorry, I sent you a typo in my August 25 2016 comment. It should have said:
    It should have said
    To > Chart.ChartType = xlPie

  22. Raspreet Singh Jaggi
    October 21, 2016 at 3:22 PM — Reply

    Your codes are very much helpful Mr.PNRao.

  23. Dwayne
    November 29, 2016 at 10:01 AM — Reply

    Hi all,
    That was quite a read! I’ve come away with many ideas for future spreadsheets..

    I do have one quick query, I’m using the following script to change the data range for a chart I’m using;

    Sub RECPLINE()
    ActiveSheet.ChartObjects(“Chart 1”).Activate
    ActiveChart.SeriesCollection(1).Select
    ActiveChart.SetSourceData Source:=Range(“=Data!$AR$3:$AW$31”)
    End Sub

    Instead of having 6 charts crammed into one screen, I aim to have one chart and 6 buttons to change the data range in the chart.
    Everything works fine, but I have formatted the visual aspects of the chart to be more appealing. After saving and re-opening the spreadsheet, the first chart has kept the formatting, but all the other charts adopt the standard formatting when the data range is changed..

    Is there any way I can force the existing visual changes, or will I have to code the changes into the VBA script each time I change the data range?

    Any help would be greatly appreciated!

    Cheers,
    Dwayne.

  24. Rommel Pastidio
    January 29, 2018 at 1:47 PM — Reply

    Hi PNrao,

    The codes here is very useful, for now I am creating excel with VBA for charting. can you help me with below inquiry?
    1. if I plot a chart using VBA how can I add comment on the point (if out of specs)?

  25. anil reddy
    March 28, 2019 at 5:47 PM — Reply

    hi PNrao

    how to do data validation using vba

  26. paulus
    May 20, 2019 at 12:21 PM — Reply

    how can i specify range for x-axis and for y-axis when coding for a line graph, and all my data in rows. for example row 1 is my x-axis and row 2 is my y-axis?

  27. amol
    June 3, 2019 at 4:29 PM — Reply

    sBody = ” ”

    Can you please explain above code…

  28. amol
    June 3, 2019 at 4:30 PM — Reply

    Mid(sImgPath, InStrRev(sImgPath, “) + 1)

    kindly explain the above code…

  29. PNRao
    July 4, 2019 at 6:10 PM — Reply


    Sub ttt()

    'Let us say, you have the file path and name asigned to the variable
    sImgPath = "C:MainFolderSubFolderYourFileName.xlsm"

    'You can extract the filename using the given code
    Filename = Mid(sImgPath, InStrRev(sImgPath, ") + 1)

    'Explaination
    'InStrRev function checks find the fist finding posing of the given string (") in the sImgPath from the right
    'i.e; InStrRev(sImgPath, ") expression results the value 24 in the above code
    'And the mid function will return the substing from the given starting positions
    '.ie;Mid(sImgPath,24+1) returns the substing of sImgPath from the 25th position
    '="YourFileName.xlsm"

    End Sub

  30. PNRao
    July 4, 2019 at 6:12 PM — Reply

    This will assign blank space to the sBody variable.

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Понравилась статья? Поделить с друзьями:
  • Vba excel создание файла word
  • Vba excel создание ссылки
  • Vba excel создание списков
  • Vba excel создание списка
  • Vba excel создание пользовательской формы