You draw a chart in Excel VBA by creating a ChartObject on a worksheet and then attaching a chart type to it with .Chart.ChartType, or by adding a Chart object to the workbook's Charts collection for a standalone sheet. The shortest working pattern is Set cht = ActiveSheet.ChartObjects.Add(Left:=100, Top:=50, Width:=400, Height:=250), then cht.Chart.SetSourceData Source:=Range("A1:B10") and cht.Chart.ChartType = xlColumnClustered. That gives you an embedded chart you can format, name and reposition from code.
This is useful when you build reports repeatedly: instead of clicking Insert > Chart by hand each time, one macro can size the chart, bind it to a growing data range, apply your house colours and export or print it. Labels in the Excel ribbon and dialog boxes can differ slightly by version, device and region, but the VBA object model described here has been stable across recent Excel releases on Windows and Mac.
What You'll Need
- Excel desktop (Windows or Mac). VBA macros do not run in Excel for the web, and the browser version cannot record or edit them.
- The Developer tab enabled: File > Options > Customize Ribbon, then tick Developer in the right-hand list. On Mac, Excel > Preferences > Ribbon & Toolbar.
- A workbook saved as
.xlsm(macro-enabled) if you want the code to persist. A plain.xlsxloses macros when saved. - Source data laid out cleanly: one header row, numbers in a single block, no blank rows inside the range, and dates or text in the category column.
- Macro security permitting macros. If the file is blocked, check File > Info for a security banner before assuming the code is broken.
Step-by-Step
- Open the editor. On the Developer tab click Visual Basic, or press Alt+F11 (Windows) or Option+F11 (Mac). Insert > Module to get a blank code window. Keep chart code in a standard module rather than a sheet module unless it must fire on an event.
- Reference the worksheet explicitly. Start with
Dim ws As WorksheetandSet ws = ThisWorkbook.Worksheets("Data"). Relying onActiveSheetwhile you debug is fine, but names avoid surprises when someone clicks another tab. - Delete any old chart with the same name so re-running the macro does not stack charts:
On Error Resume Next,ws.ChartObjects("SalesChart").Delete,On Error GoTo 0. The error handling matters because deleting a name that does not exist raises an error. - Create the chart container.
Dim cht As ChartObjectthenSet cht = ws.ChartObjects.Add(Left:=200, Top:=50, Width:=420, Height:=280). These numbers are points, not pixels; the chart lands 200 points from the left edge and 50 from the top. - Name it. Set
cht.Name = "SalesChart"immediately after creation. Naming makes the chart findable later, both in VBA and in the Name Box in the Excel window. - Bind the data.
cht.Chart.SetSourceData Source:=ws.Range("A1:B10"). Include the header row so Excel picks up series names and the axis title automatically. For dynamic ranges usews.Range("A1").CurrentRegionor compute the last row withws.Cells(ws.Rows.Count, 1).End(xlUp).Row. - Choose the chart type.
cht.Chart.ChartType = xlColumnClusteredfor bars,xlLinefor trends,xlPiefor one series only,xlXYScatterfor two numeric axes. These are built-in constants; typing them in the editor gives you autocomplete so you can browse the list. - Add titles and legend.
cht.Chart.HasTitle = Truethencht.Chart.ChartTitle.Text = "Monthly Sales". Toggle the legend withcht.Chart.HasLegend = True. For a pie chart showing percentages, add data labels:cht.Chart.SeriesCollection(1).HasDataLabels = True. - Format sparingly and specifically. Colours are set per series:
cht.Chart.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(31, 78, 121). For a fixed axis scale usecht.Chart.Axes(xlValue).MinimumScale = 0. Avoid looping over every element — name only what you need. - Place it deliberately.
cht.Left = ws.Range("D2").Leftandcht.Top = ws.Range("D2").Topanchors the chart to a cell so it moves with the layout. For a full-width report chart, setcht.Widthto roughly the width of the used columns. - Run it. Press F5 with the cursor inside the routine, or attach it to a button via Developer > Insert > Button (Form Control). Step through with F8 to catch errors one line at a time.
- Save as macro-enabled. Use File > Save As and choose Excel Macro-Enabled Workbook (
.xlsm). Test by closing and reopening — if the chart appears on the sheet but the macro is gone, the file was saved in the wrong format.
Common Mistakes
Forgetting that ChartObject and Chart are different objects. Size, position and name belong to the ChartObject; data, type, titles and series belong to .Chart. Mixing them up produces "Object doesn't support this property or method". If cht.Width works but cht.ChartType does not, you have the layers confused.
Using SetSourceData with a range that excludes headers. The chart then shows "Series1" and loses axis titles. Include the header row, or set series names explicitly.
Building on the active sheet by accident. If the macro runs while a different tab is visible, ActiveSheet.ChartObjects.Add puts the chart in the wrong place. Always qualify with a worksheet variable.
Leaving stale charts behind. Running the macro three times leaves three overlapping charts. Delete by name first, as in step 3.
Assuming the macro travels with copied data. Copying the sheet into a new workbook often drops or re-links the macro. Rebuild or re-import the module.
Tips
- Record a throwaway macro (Developer > Record Macro) while formatting a chart by hand, then read the generated code to learn the exact property names — much faster than guessing.
- Keep chart-building in a reusable
Subthat takes the range, sheet and chart type as arguments, so one macro serves every report. - Set
cht.Chart.PlotVisibleOnly = Trueif you hide rows or columns and want the chart to ignore them. - If the chart is for printing, set the chart object's
PlacementtoxlMoveAndSizeso it resizes with the cells around it. - Export charts without opening Excel's UI:
cht.Chart.Export "C:\Reports\chart.png"writes a PNG, though the path must exist and be writable.
Troubleshooting
"Subscript out of range" on the worksheet name. The tab name in the code does not match the workbook exactly — watch for trailing spaces or a renamed tab. Use ThisWorkbook.Worksheets(1) while testing.
The chart is blank. The range reference is probably empty or points at the wrong sheet. Print ws.Range("A1:B10").Address before binding, and check that the cells hold numbers rather than text. Text-formatted numbers plot as zero or nothing.
"Method 'ChartObjects' of object '_Worksheet' failed". The sheet is usually protected or the workbook is in a state that blocks edits. Unprotect the sheet with ws.Unprotect (prompting for a password if one is set) and re-run.
The macro does not appear in the list. It is likely in a sheet or workbook module rather than a standard module, or the workbook is blocked. Check File > Info for the security banner and enable content only for files you trust.
Formatting code errors only on Mac. Some chart APIs are implemented differently; test the visual result rather than assuming the same property returns the same thing, and keep formatting minimal if the file must run on both platforms.
If that did not work, delete the chart object, comment out all formatting lines, and run just the create-bind-type sequence. Once that produces a bare chart, add formatting back one line at a time to find the offending property.
Frequently Asked Questions
Can I create a chart on its own sheet instead of inside a worksheet?
Yes. Use Charts.Add to add a chart sheet, then set .SetSourceData and .ChartType on it. Chart sheets are separate tabs and cannot be positioned over cells.
Why does my macro draw two charts each time I run it?
Because the existing chart was not removed. Delete the ChartObject by name at the start of the routine, or check whether it exists with a loop before adding.
Does VBA chart code work in Excel for the web?
No. Macros are not supported in the browser version. Use Excel desktop, then open the file in the browser to view the result.
How do I make the chart follow a growing data range?
Use CurrentRegion or compute the last row and build the range with ws.Range(ws.Cells(1,1), ws.Cells(lastRow, 2)). Re-run the macro after data changes.
Can I set chart colours to match my brand automatically?
Yes, per series with RGB() values on SeriesCollection(n).Format.Fill.ForeColor. Loop over series only if the count is fixed; if it varies, wrap the loop in a count check.