View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
semiopen semiopen is offline
external usenet poster
 
Posts: 25
Default dynamic chart range with VBA


Jacob wrote:
I have been spending a lot of time trying to figure out dynamic chart
ranges and just can't figure it out. I have a chart (scatter plot)
that needs to have the X and Y values of a series linked to the number
of values present, which will be constantly changing. It would also be
nice to have the maximum/minimum scale adjustable as well, for both
axes. the code I am using (below) is causing errors.

Private Sub UpdateChart()
span = Sheets("sheet1").Range("C4").Value * 12
stepsize = Sheets("sheet1").Range("C6").Value * 12
Set CurrentChart = Sheets("sheet2").ChartObjects(1).Chart
CurrentChart.Parent.Width = 450
CurrentChart.Parent.Height = 150

'ActiveChart.SeriesCollection(1).XValues = "=Sheet2!R2C2:R2C" & 2
+_
(span / stepsize) & ""
'ActiveChart.SeriesCollection(1).Values = "=Sheet2!R1C2:R1C" & 2 +
_
(span / stepsize) & ""

ActiveChart.Axes(xlCategory).Select
With ActiveChart.Axes(xlCategory)
.MinimumScale = 0
.MaximumScale = span / stepsize + 1
.MinorUnit = 12
.MajorUnit = 24
.Crosses = 0
End With

' Save chart as GIF
Fname = ThisWorkbook.Path & Application.PathSeparator & "temp.gif"
CurrentChart.Export Filename:=Fname, FilterName:="GIF"

' Show the chart
Image3.Picture = LoadPicture(Fname)
End Sub


1) Why did you set CurrentChart then switch to ActiveChart? Using
CurrentChart would be more consistent.

2) Replace "=Sheet2!R2C2:R2C" & 2 + (span / stepsize) & ""
by "=Sheet2!R2C2:R2C" & (2 + (span / stepsize)) & """

Note the extra double quote - "" is the empty string

3) A more radical suggestion: when you create the chart, let the X and
Y values be *names*. For example, I have a chart (involving dice
probabilities) where I created a chart and typed this in the source
data under series/X Values:

='Dice Sums.xls'!xvals

And the same thing for y (but with "y" of course). "xvals" is the name
of the range which is to contain the xvals.
Then - in the code I create a Range variable xRange and, after loading
it with what I want by a combination of the Range function and Offset
something like:

Set xRange = Range(Range("A1"),Range("A1").Offset(k))

I simply use the statement

xRange.Name = "xvals"

and now the Chart will have the right x-vals

Hope that helps

-semiopen