How to set X axis programmatically on a chart?
Question
I have a chart in a Worksheet in Excel and I have a macro set up so that when I change the value in a certain cell the range of data in the chart is set to A2
down as far as the row number corresponding in this certain cell.
What I can't seem to be able to do is to modify the axis as the specified axis no longer covers the range of the graph i.e. the current X axis is set to:
=Sheet1!$C$2:$C$600
I can't figure out how I can update this in a macro. Any help would be much appreciated.
Solution
You should be able to set the XValues property in the same way you did in Lance's answer for your other question.
Charts("chartname").SeriesCollection(1).XValues = "=MYXAXIS"
or whatever you call the named range for the x-axis values. If you have multiple series in your chart, you'll want to change the value in SeriesCollection to refer to the right series.
OTHER TIPS
Does the "certain cell" contain the last row number of the data? (it isn't quite clear)
Suppose cell F1 contains the last row in the data. You can construct an address and range like this:
Dim rXVals As Range
Dim sAddress AS String
sAddress = "Sheet1!$C$2:$C$" & Worksheets("Sheet1").Range("F1").Value
Set rXVals = Range(sAddress)
Worksheets("Sheet1").ChartObjects(1).Chart.SeriesCollection(1).XValues = rXVals