PDA

View Full Version : Creating a graph from a selection



chamster
09-12-2007, 08:11 AM
I'm running the following code and as far i can see, it should work. The computer disagrees and, unfortunately, it wins. Where do i go wrong?

Sub CreatePlot()
Dim chrt As Chart
Set chrt = Charts.Add
chrt.ChartType = xlXYScatter
chrt.SetSourceData Source:=Selection.CurrentRegion, PlotBy:=xlColumns
chrt.Location Where:=xlLocationAsObject, Name:="Kvalit?er"
chrt.HasLegend = False
End Sub

The strange part is that i get to see the graph, only as a separate sheet. So, it seems that the selection gives data to the plot. Still, it's on the line with .SetDataSource that i get the error. Something about 438: The object doesn't support method/property...

When i go back to Excel and manually set the active sheet to be the one with the data, it works through the line so i'm suspecting that the error should be somewhere there.

But then again, as i start to continue, i get errors at .HasLegend.

chamster
09-12-2007, 08:44 AM
Now that i've laborated with the issue i see that what makes the difference is this line.

chrt.Location Where:=xlLocationAsObject, Name:="Kvalit?er"

After this line, i need to refer to the chart by ActiveChart, before, as the given name, namely chrt. Can some good soul shed some light onto this for me, please?

mdmackillop
09-12-2007, 11:05 AM
You can't use Selection after the chart is created as Selection is lost. Set a variable to "remember" this location. Name has a meaning when the chart is on its own sheet; I'm not sure it is valid when inserted in a sheet (although I may be wrong!)

Option Explicit

Sub CreatePlot()
Dim chrt As Chart, Rng As Range, ws As Worksheet

Set ws = ActiveSheet
Set Rng = Selection
Set chrt = Charts.Add

With chrt
.SetSourceData Source:=Rng.CurrentRegion, PlotBy:=xlColumns
.Name = "Kvalit?er"
.ChartType = xlXYScatter
.HasLegend = False
.Location Where:=xlLocationAsObject, Name:=ws.Name
End With
End Sub

chamster
09-12-2007, 11:40 PM
Ah, much clearer now. Thanks!