1

I'm working with chart in Excel/Vba and I've got this chart causing troubles : enter image description here

I want the X value (B/C/D/E/F) to fit all the graph width. Does anyone has a macro for that ?

Melanie Journe
  • 1,249
  • 5
  • 16
  • 36

2 Answers2

1

Turn your source data into an Excel Table object with Ctrl-T or Insert > Table. Then create the chart based on the table.

enter image description here

When you add more data to the table, the chart will refresh. The X axis of the chart will only show data that exists in the table.

The crucial bit here is to NOT pre-populate the table with rows that don't yet have values for the chart. so don't put in empty rows where you only have a label in column A, but no values for the series.

If your data table has empty rows, you can filter the table to show only rows with data, and the chart will ignore the rows that are filtered out. See how rows 7 and 8 are not showing in the filtered table and the chart shows the x values f and i without any gap in the charting lines.

enter image description here

teylyn
  • 34,374
  • 4
  • 53
  • 73
1

Use the SetSourceData function to update the range of the chart.

Example data set with 'unwanted' items: enter image description here

VBA to update the source data:

Option Explicit

Sub Test()

    Dim ws As Worksheet
    Dim chto As ChartObject
    Dim cht As Chart

    Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- update to your sheet
    Set chto = ws.ChartObjects("Chart 1") '<-- update to your chart
    Set cht = chto.Chart
    cht.SetSourceData Source:=ws.Range("A1:F2") '<-- update to your range

End Sub

Updated example: enter image description here

Other relevant questions:

Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56