Table of Contents
Understanding the Core VBA Syntax for Chart Generation
Automating tasks within Microsoft Excel relies heavily on VBA (Visual Basic for Applications), a robust programming language designed specifically to extend Excel’s native capabilities. A frequent automation requirement involves the programmatic creation of data visualizations, such as a bar chart or column chart. The foundational syntax required to instantiate and configure such a chart object is remarkably efficient, primarily focusing on defining the underlying data source and explicitly specifying the desired chart type enumeration.
The code structure demonstrated below provides the essential framework for generating a chart object directly within a designated worksheet. This process utilizes the crucial ChartObject class, which serves as a necessary container for the actual visual chart. This container allows the chart to be precisely resized, moved, and positioned within the structured Excel grid. Furthermore, incorporating the Application.InputBox method ensures the macro is interactive, dynamically prompting the user to select the required data range at runtime. This interactive approach significantly enhances the code’s flexibility and ensures it remains reusable across diverse datasets without modification.
We begin by reviewing the fundamental VBA module below. This script acts as the foundational blueprint for our automated charting application, illustrating the core logic of object declaration and initialization:
Sub CreateBarChart()
Dim MyChart As ChartObject
'get input range from user
Set Rng = Application.InputBox(Prompt:="Select chart input range", Type:=8)
'create bar 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 = xlColumnClustered
End Sub
This macro, named CreateBarChart, is engineered to execute a precise, three-part operational sequence. First, it declares the MyChart variable as a specific ChartObject to correctly hold the generated visualization. Second, the pivotal step involves utilizing the Application.InputBox method, crucially specifying Type:=8. This numeric argument forces the input to be a valid range reference, a critical mechanism for ensuring data integrity and preventing runtime errors. Once the data range is successfully secured and stored in the Rng variable, the code proceeds to instantiate the chart container, link the data source using SetSourceData, and finally, define the chart’s visual representation.
Deconstructing the ChartObjects.Add Method
Achieving precise control over the generated chart requires a comprehensive understanding of the ChartObjects.Add method. This method is the primary function responsible for inserting the chart’s structural container onto the designated worksheet. The exact physical placement and initial sizing of the chart are governed by four mandatory positional arguments: Left, Top, Width, and Height. In the initial example script, the placement properties, Left and Top, are deliberately anchored to the current ActiveCell. This dynamic linkage ensures that the chart’s upper-left corner automatically aligns itself with the user’s active selection at the moment the macro is executed, improving user experience when defining layout.
The sequence dedicated to creation and configuration is central to the macro’s functionality. Specifically, the statement Set MyChart = Worksheets("Sheet1").ChartObjects.Add(...) executes the actual insertion of the ChartObject container into the worksheet named “Sheet1.” Immediately following insertion, the line MyChart.Chart.SetSourceData Source:=Rng establishes the essential programmatic connection between the user-selected data range (Rng) and the newly created chart visualization. This critical action populates the chart with the necessary numerical data points and corresponding category labels, preparing the visual for display and analysis.
The final configuration step dictates the specific type of visualization. The command MyChart.Chart.ChartType = xlColumnClustered specifies that the output must be a standard clustered column chart. This is Excel’s technical term for a vertical bar chart, the most common type used for comparing categorical data. If the automation required an alternative visual format, such as a line graph or a pie chart, this constant would be swapped with the relevant xlChartType enumeration member. This comprehensive sequence ensures that the chart is not only created and populated but also styled correctly according to standard data visualization best practices.
Practical Example: Automating Chart Creation from Dataset
To effectively demonstrate the power and efficiency of this VBA script, let us examine a typical scenario involving data analysis, such as tracking sports statistics. Imagine we have a straightforward dataset within an Excel worksheet detailing the points scored by several basketball players across a season. Our primary goal is to leverage the macro developed previously to generate a visual representation of this performance data quickly, thereby facilitating rapid comparison and interpretation of player statistics.
The required data structure for this task is simple and effective, typically organized into two adjacent columns: one column dedicated to the player names (serving as categories) and the corresponding adjacent column containing the points scored (representing the values). This two-column format, as illustrated in the image below, is perfectly suited for a clustered column chart, as it provides a clear, one-to-one mapping of categorical identifiers to numerical magnitude. Utilizing VBA for this task is a significant time-saver, completely eliminating the necessity for tedious manual steps—such as navigating the Excel ribbon, choosing the chart type, and manually selecting the data range—thereby dramatically boosting workflow efficiency.

Given this structured dataset, the next step is to integrate the exact macro code into a standard module within the VBA Editor. The objective remains unwavering: prompt the end-user for the range encompassing both the player names and their scores, and then autonomously generate the visualization anchored relative to the active cell. The core benefit highlighted here is the inherent reusability of the code; the structural commands required for chart creation remain functionally constant, regardless of the specific content or size of the underlying data.
For this specific practical demonstration, the macro utilized remains functionally identical to the generalized structure defined in the preceding section, reinforcing the standardized approach to chart automation:
Sub CreateBarChart()
Dim MyChart As ChartObject
'get input range from user
Set Rng = Application.InputBox(Prompt:="Select chart input range", Type:=8)
'create bar 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 = xlColumnClustered
End SubStep-by-Step Execution of the VBA Macro
Executing the automated routine requires accessing the Excel Developer environment. Depending on the user’s installation configuration, the Developer tab may need to be enabled in Excel options. Once the macro code has been successfully saved within a standard module, the process of initiating the script is extremely straightforward, ensuring that even users with minimal technical background can utilize the powerful automation benefits provided by the script.
The standardized procedure for launching the CreateBarChart macro involves following these precise steps:
Ensure the target worksheet (in this example, Sheet1) is the active sheet displayed to the user.
Navigate to and click on the Developer tab, which is located in the main Excel ribbon interface.
Select the Macros button (often found within the Code group) to open the comprehensive Macro dialog box.
Locate and distinctly select the macro procedure titled CreateBarChart from the list.
Click the Run button to initiate the automated script execution sequence.
The visual representation below demonstrates the required interaction with the dialog box, showing the necessary steps for selecting and executing the CreateBarChart procedure from the list of available macros stored within the current workbook environment.

Immediately upon clicking Run, the script executes until it encounters the critical Application.InputBox command. This command halts the macro’s progression and displays a custom prompt to the user, explicitly requesting the required input data range. Because we thoughtfully included the argument Type:=8, this specialized input box is optimized to accept a graphical range selection directly from the worksheet, though typing the range address manually remains a viable alternative.

For our example focusing on player statistics, which includes both player names and points scored, the appropriate input range is A1:B7. Once this specific range is entered into the prompt and confirmed by selecting OK, the subsequent lines of the macro execute without further intervention. The script automatically proceeds to create the ChartObject container, dynamically assign the selected data, and accurately set the chart type to xlColumnClustered, thereby finalizing the entire visualization process.
Customizing Chart Properties and Dimensions
The immediate result generated by the macro is a fully functional column chart, automatically positioned relative to the cell that was active at the moment of script initiation. In this specific demonstration, if the user had selected cell D1 prior to running the macro, the chart’s top-left corner would be dynamically aligned with that cell’s coordinates, as dictated by the use of ActiveCell.Left and ActiveCell.Top within the ChartObjects.Add parameters.
The resulting visualization provides an instant, clear display for comparing the points scored by each player, offering a high-impact visual summary of the numerical data:

One of the most accessible and immediate customization features available within the ChartObjects.Add() function is the control over the physical dimensions of the inserted chart. The arguments Width and Height define the size in points and directly govern the overall bounding box of the ChartObject container. In the provided script, these dimensions were initially set to 400 points wide and 300 points high. Developers routinely adjust these values to ensure the chart fits precisely within standardized dashboard layouts, presentation slides, or defined print areas.
For advanced, post-creation customization, virtually all properties of the chart can be manipulated programmatically. For example, rather than relying on the user’s active selection, the placement of the chart can be fixed to absolute coordinates on the worksheet. This is achieved by replacing ActiveCell.Left and ActiveCell.Top with fixed numerical values (e.g., Left:=50, Top:=50), guaranteeing the chart appears in the same location consistently. Moreover, elements such as the chart title, axis labels, specific data series colors, and scaling can all be precisely managed via subsequent VBA commands applied to the nested MyChart.Chart property, granting the developer complete control over the final visual design.
Summary and Key Next Steps
The capability to programmatically generate data visualizations using VBA is foundational for streamlining and standardizing data reporting workflows within Excel. By systematically leveraging robust objects such as the ChartObject and sophisticated methods like Application.InputBox, developers can construct flexible, standardized charting utilities that demand minimal manual input from the end-user. The procedural execution involves several key stages: declaring the object, securing the required data range dynamically, adding the container to the sheet, assigning the data source using SetSourceData, and finally, specifying the exact chart type using enumerations like xlColumnClustered.
Mastering this core syntax enables the rapid creation of various chart types, seamlessly transforming raw tabular data into highly informative visual summaries with maximum efficiency. For developers looking to expand their automation capabilities beyond simple clustered column charts (vertical bar chart), the next logical phase of learning involves exploring the vast range of other available chart types and implementing advanced formatting and conditional logic techniques.
The following resources are recommended for continuing your journey into Excel automation, providing additional tutorials and detailed explanations on performing other common and advanced tasks using VBA:
Strategies for automating complex worksheet formatting and styling.
Effective implementation of data structures like arrays and dictionaries in VBA programming.
Programmatic creation, manipulation, and updating of Pivot Tables for data summarization.
Applying advanced data manipulation techniques using iterative loops and conditional logic structures.
Cite this article
Mohammed looti (2025). Creating Bar Charts with VBA in Excel: A Step-by-Step Tutorial. PSYCHOLOGICAL STATISTICS. Retrieved from https://statistics.arabpsychology.com/create-a-bar-chart-in-vba-with-example/
Mohammed looti. "Creating Bar Charts with VBA in Excel: A Step-by-Step Tutorial." PSYCHOLOGICAL STATISTICS, 15 Nov. 2025, https://statistics.arabpsychology.com/create-a-bar-chart-in-vba-with-example/.
Mohammed looti. "Creating Bar Charts with VBA in Excel: A Step-by-Step Tutorial." PSYCHOLOGICAL STATISTICS, 2025. https://statistics.arabpsychology.com/create-a-bar-chart-in-vba-with-example/.
Mohammed looti (2025) 'Creating Bar Charts with VBA in Excel: A Step-by-Step Tutorial', PSYCHOLOGICAL STATISTICS. Available at: https://statistics.arabpsychology.com/create-a-bar-chart-in-vba-with-example/.
[1] Mohammed looti, "Creating Bar Charts with VBA in Excel: A Step-by-Step Tutorial," PSYCHOLOGICAL STATISTICS, vol. X, no. Y, ص Z-Z, November, 2025.
Mohammed looti. Creating Bar Charts with VBA in Excel: A Step-by-Step Tutorial. PSYCHOLOGICAL STATISTICS. 2025;vol(issue):pages.