Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Edit Chart Data: A Complete Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To edit chart data using Excel VBA, you primarily manipulate the SetSourceData method of the Chart object or modify the Formula property of a specific Series object. This allows you to dynamically change the range of cells a chart references, add new data points, or switch between different data sets without manually clicking through the Select Data dialog box. This is essential for creating automated dashboards where the data range expands as new rows are added daily or monthly.

What You'll Need

  • Microsoft Excel installed on a Windows or Mac computer.
  • The Developer tab enabled in the Excel Ribbon (Right-click any tab > Customize the Ribbon > Check 'Developer').
  • A workbook containing at least one existing chart and a dataset to link to it.
  • Basic familiarity with the VBA Editor (ALT + F11).

Step-by-Step

  1. Open the VBA Editor: Press ALT + F11 on your keyboard to launch the Visual Basic for Applications environment.
  2. Insert a New Module: In the Project Explorer on the left, right-click your workbook name, select Insert, and then click Module. This is where you will write your code to ensure it is accessible throughout the workbook.
  3. Define Your Variables: Start your subroutine by declaring variables for your worksheet, your chart, and your data range. Using specific object types (like ChartObject) prevents errors and enables IntelliSense.
    Dim ws As Worksheet
    Dim myChart As Chart
    Dim dataRange As Range
  4. Assign the Objects: Set your variables to the actual elements in your workbook. For example, if your chart is on Sheet1 and your data is in columns A through B, use:
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Set myChart = ws.ChartObjects("Chart 1").Chart
    Set dataRange = ws.Range("A1:B10")
  5. Apply the Source Data: Use the SetSourceData method to update the entire chart's reference. The syntax is myChart.SetSourceData Source:=dataRange. This is the fastest way to update both the X and Y axes simultaneously.
  6. Target a Specific Series (Advanced): If you only want to change the values for one specific line or bar in a multi-series chart, avoid SetSourceData and use the FullSeriesCollection.
    myChart.FullSeriesCollection(1).Values = "=Sheet1!$B$2:$B$10"
    Note that when assigning values to a series via VBA, you must provide the reference as a string starting with an equals sign, mimicking a standard Excel formula.
  7. Handle Dynamic Ranges: To make the chart update automatically as you add data, replace the static range (A1:B10) with a dynamic calculation. You can use End(xlDown) to find the last row of data:
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    Set dataRange = ws.Range("A1:B" & lastRow)
    myChart.SetSourceData Source:=dataRange
  8. Run the Code: Press F5 or click the Play button in the toolbar to execute the script. Your chart should now reflect the updated range.

Common Mistakes

One of the most frequent errors is confusing the ChartObject with the Chart object. A ChartObject is the container (the rectangle sitting on the sheet), whereas the Chart is the actual data visualization inside that container. If you try to call SetSourceData on a ChartObject, VBA will throw a "Method or data member not found" error. Always ensure you append .Chart to your reference.

Another common pitfall is failing to account for headers. When using SetSourceData, if your range includes the top row, Excel usually guesses whether those are headers. If your chart suddenly starts treating your labels as data points, you may need to explicitly define the series values and category labels separately rather than using the bulk source data method.

Hard-coding sheet names is also a risk. If a user renames "Sheet1" to "Sales Data", your code will crash. To avoid this, use the Code Name of the sheet (the name shown outside the parentheses in the VBA Project Explorer) or assign the sheet to a variable based on its index number.

Tips

To create a truly professional automated report, combine your chart update code with a Worksheet_Change event. By placing the code in the Sheet module instead of a standard module, the chart will update the very instant a value is changed in the data table, removing the need for the user to click a button.

When dealing with very large datasets, turning off screen updating can significantly speed up the execution of your macro. Use Application.ScreenUpdating = False at the start of your code and set it back to True at the end. This prevents the screen from flickering as the chart redraws itself.

If you are frequently changing the data source, consider using Excel Tables (Ctrl + T). When a chart is linked to a Table, it becomes a "Dynamic Chart." In many cases, you won't even need VBA to edit the data range because the chart will automatically expand as new rows are added to the Table. VBA can then be used for more complex tasks, such as switching the Table's filter criteria.

Troubleshooting

If the code runs without errors but the chart does not change, first verify the name of the chart. Right-click the chart and look at the Name Box (top left of the Excel grid). If it says "Chart 2" but your code refers to "Chart 1", the macro will either fail or update the wrong object. Ensure the string in ChartObjects("Name") matches exactly.

If you receive a "Global" or "Object Required" error, check your Set statements. In VBA, when assigning an object (like a Range or Worksheet) to a variable, you must use the Set keyword. Writing ws = Sheets("Sheet1") instead of Set ws = Sheets("Sheet1") will cause the code to fail immediately.

If the chart values appear as zeros or the series disappears, check the formatting of your source data. VBA is strict about data types; if your numbers are stored as text, the Values property of the series may not recognize them. Use the Value = Value trick in a loop or the TextToColumns method to convert text-numbers back into actual numeric values before updating the chart.

In cases where the chart is on a separate Chart Sheet (rather than embedded in a worksheet), the referencing logic changes. You do not use ChartObjects; instead, you reference the chart directly via Charts("ChartName"). If you are switching between embedded charts and chart sheets, ensure your variable declarations match the object type.

Frequently Asked Questions

Can I change the chart type while editing the data?

Yes. You can use the myChart.ChartType property. For example, myChart.ChartType = xlColumnClustered will change the chart to a clustered column chart immediately after the data is updated.

How do I add a completely new series to an existing chart?

Use the SeriesCollection.NewSeries method. This creates a new blank series which you can then define by setting its .Values and .XValues properties to specific ranges.

Can VBA edit charts in a closed workbook?

No, the workbook containing the chart must be open in the current Excel instance for VBA to manipulate the Chart objects. You can use Workbooks.Open("path") to open the file first.

How do I clear all data from a chart using VBA?

You cannot "empty" a chart entirely, but you can delete all existing series using a loop: While myChart.SeriesCollection.Count > 0: myChart.SeriesCollection(1).Delete: Wend.

Why does my chart range reset when I restart Excel?

Charts usually remember their range, but if your range was set by a volatile VBA macro that doesn't save the state, it might appear reset. Ensure you save the workbook as an .xlsm (Macro-Enabled Workbook) to keep your automation scripts intact.