Table of Contents
Generating visualizations such as a pie chart directly through VBA (Visual Basic for Applications) provides immense power for automating reporting tasks within Microsoft Excel. This approach bypasses the manual steps required in the user interface, allowing for consistent, repeatable chart creation based on dynamic datasets.
The process of creating an embedded chart using VBA is straightforward but requires understanding key object models. Initially, you must ensure your underlying data is correctly structured in an Excel worksheet. Following data preparation, you define a procedure (a macro) that utilizes the ChartObject class to programmatically insert, size, and define the data source for your chart. Finally, you set the chart type, which, in this case, will be specified as a pie chart.
By mastering the use of the ChartObject and related properties, you gain precise control over the chart’s appearance, placement, and data linkage, making automation robust and reliable for complex analytical reports.
Understanding the Core Components of VBA Chart Generation
The foundation of automating visualizations in Excel relies on manipulating objects defined within the Excel Object Model. To create any chart, you interact primarily with the ChartObject container, which holds the actual chart itself. This object allows you to specify physical attributes like position, width, and height on the worksheet, ensuring the chart integrates seamlessly into your reporting layout.
The following basic syntax demonstrates the use of core commands required to initiate the creation of a pie chart using VBA. This structure is essential for defining variables, prompting user input, and finally, rendering the visualization.
Sub CreatePieChart()
Dim MyChart As ChartObject
'get input range from user
Set Rng = Application.InputBox(Prompt:="Select chart input range", Type:=8)
'create pie chart
Set MyChart = Worksheets("Sheet1").ChartObjects.Add(Left:=ActiveCell.Left, _
Width:=400, Top:=ActiveCell.Top, Height:=300)
MyChart.Chart.SetSourceData Source:=Rng
MyChart.Chart.ChartType = xlPie
End Sub
This macro encapsulates several key actions: defining an object variable, obtaining the data range, creating the chart container, linking the data, and setting the specific chart type using the constant xlPie. Understanding the purpose of each line is critical for effective chart automation in VBA.
Detailed Syntax Breakdown: The Chart Generation Macro
Let us analyze the individual lines of the macro above to fully appreciate how the automated chart is constructed. The procedure begins with the declaration of variables, a fundamental practice in structured programming.
`Sub CreatePieChart()`: This line simply names and starts the macro procedure.
`Dim MyChart As ChartObject`: The Dim statement declares the variable
MyChartas a specific object type: a ChartObject. This is the container that will hold the visual chart within the worksheet.`Set Rng = Application.InputBox(Prompt:=”Select chart input range”, Type:=8)`: This line utilizes the
Application.InputBoxmethod to ask the user to visually select the data range directly from the spreadsheet. TheType:=8argument specifies that the input expected is a Range object, ensuring data integrity.`Set MyChart = Worksheets(“Sheet1”).ChartObjects.Add(…)`: This is the core creation command. It uses the
Addmethod of theChartObjectscollection on “Sheet1” to physically place the chart container. The argumentsLeft,Width,Top, andHeightdetermine the chart’s position and size. By settingLeftandTopequal toActiveCell.LeftandActiveCell.Top, the chart is anchored to the top-left corner of the currently selected cell.`MyChart.Chart.SetSourceData Source:=Rng`: Once the chart container exists, this line links the user-selected data range (
Rng) to the chart. The.Chartproperty provides access to the actual graphical chart attributes.`MyChart.Chart.ChartType = xlPie`: This crucial step defines the visualization style. We assign the built-in VBA constant xlPie to the
ChartTypeproperty, instantly converting the generic chart into a pie chart.
The use of the Dim statement, combined with precise object referencing, ensures that this automation is both clean and efficient, preventing runtime errors and memory issues.
Setting Up Your Data for a Practical Example
To illustrate the functionality of the macro, we will use a sample dataset. For a pie chart to be meaningful, the data typically requires one column for categories (text labels) and one column for corresponding numerical values (the magnitudes that determine slice size). In this example, we track points scored by different basketball players.
Suppose we have the following dataset organized within an Excel worksheet, starting at cell A1:

This structured data is perfectly suited for a pie chart, where the ‘Player’ names will serve as category labels and the ‘Points Scored’ will determine the percentage represented by each slice. Our objective is to generate the chart automatically using VBA, prompting the user for the range A1:B7.
While the previous macro asked the user for the input range, for fixed reports, you could hard-code the range directly into the macro, removing the need for the Application.InputBox. However, the interactive nature of the macro below ensures flexibility across different worksheets.
Implementing and Running the VBA Macro
We will use the same robust macro structure discussed previously to generate the chart based on the basketball dataset. This macro is placed within a standard module in the VBA Editor (accessible via Alt + F11).
We can create the following macro to execute this task:
Sub CreatePieChart()
Dim MyChart As ChartObject
'get input range from user
Set Rng = Application.InputBox(Prompt:="Select chart input range", Type:=8)
'create pie chart
Set MyChart = Worksheets("Sheet1").ChartObjects.Add(Left:=ActiveCell.Left, _
Width:=400, Top:=ActiveCell.Top, Height:=300)
MyChart.Chart.SetSourceData Source:=Rng
MyChart.Chart.ChartType = xlPie
End SubTo initiate this automation, you must access the Developer tab in the Excel ribbon. If this tab is not visible, you may need to enable it through Excel Options. The execution steps are clearly defined:
- Click on the Developer tab located along the top ribbon in Excel.
- Then, click the Macros button within the Code group.
- Select the macro titled CreatePieChart from the list.
- Finally, click the Run button to execute the procedure.
Upon execution, the macro immediately reaches the Application.InputBox line, prompting the user for the required data range.
Analyzing the Output and Customizing Chart Placement
Once we click Run, the interactive dialog box appears, requesting the input range for the chart generation. This is a critical step where we define which cells contain the data the chart will visualize.
The prompt will look similar to this:

For our specific dataset, we must accurately input the range A1:B7 into the input box, ensuring we include both the header row and all data rows. After entering the range and pressing OK, the macro proceeds to create the ChartObject.
The position of the new chart is determined by the active cell at the moment the macro runs. If the active cell happens to be cell D2, the top-left corner of the newly created ChartObject will align precisely with the top-left corner of cell D2. The resultant chart, reflecting the points scored by the players, will automatically be displayed on the worksheet:

The ability to dynamically anchor the chart to the ActiveCell is extremely useful for users who need to place reports in different locations without having to modify the underlying code.
Advanced Customization and Best Practices for VBA Charts
While the initial macro successfully creates a functional pie chart, real-world reporting often requires extensive visual customization, including adjustments to size, titles, colors, and data labels. All these modifications can and should be handled programmatically within the VBA procedure to maintain automation consistency.
One immediate customization option involves controlling the physical size of the chart. The dimensions are defined in the ChartObjects.Add() function:
- The Width argument (set to 400 in the example) defines the horizontal dimension of the chart in points.
- The Height argument (set to 300 in the example) defines the vertical dimension of the chart in points.
Note: You can easily change the numeric values for the Width and Height arguments within the ChartObjects.Add() function to precisely adjust the physical dimensions of the pie chart.
Beyond simple sizing, further improvements usually involve accessing the chart properties after the source data has been set:
Adding a Title: Use
MyChart.Chart.HasTitle = TrueandMyChart.Chart.ChartTitle.Text = "Player Performance Summary".Applying Data Labels: Essential for a pie chart, this is achieved via
MyChart.Chart.SeriesCollection(1).HasDataLabels = True.Formatting: You can apply a built-in design style using
MyChart.Chart.ChartStyle = 201(where 201 is an example index for a specific design template).
Integrating these additional lines into the macro ensures that every time the procedure is run, a perfectly formatted, sized, and labeled chart is generated, minimizing post-creation manual effort and upholding corporate reporting standards.
Mastering chart automation using VBA is a powerful skill for any Excel user, providing the capability to generate sophisticated visualizations dynamically and reliably.
Cite this article
stats writer (2025). How to Easily Create a Pie Chart in Excel Using VBA. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-create-a-pie-chart-in-vba-with-example/
stats writer. "How to Easily Create a Pie Chart in Excel Using VBA." PSYCHOLOGICAL SCALES, 19 Nov. 2025, https://scales.arabpsychology.com/stats/how-to-create-a-pie-chart-in-vba-with-example/.
stats writer. "How to Easily Create a Pie Chart in Excel Using VBA." PSYCHOLOGICAL SCALES, 2025. https://scales.arabpsychology.com/stats/how-to-create-a-pie-chart-in-vba-with-example/.
stats writer (2025) 'How to Easily Create a Pie Chart in Excel Using VBA', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-create-a-pie-chart-in-vba-with-example/.
[1] stats writer, "How to Easily Create a Pie Chart in Excel Using VBA," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, November, 2025.
stats writer. How to Easily Create a Pie Chart in Excel Using VBA. PSYCHOLOGICAL SCALES. 2025;vol(issue):pages.
