I'm attempting to create a chart using VBA in Excel 2010. I'm attempting to select data from another sheet in the same workbook. The data, however, is horizontal (and has to be kept that way), so I need to use the Cells() function to select the data for the chart.
However, it doesn't seem to be working, and I can't really find out why. I keep getting the error "Application-Defined or Object-Defined error" on any line that uses the Cells() function to define a range. However, if Cells() is used to reference a single cell, it works fine.
Can Range(Cells(x, y), Cells(z, w)) not be used in this case?
Here is the relevant code:
BinNumber = 2048
Worksheets("Graph One").Activate
Range("A1").Select
'Setting the range the chart will cover
Set rngChart = ActiveSheet.Range("H2:U26")
'Dimensioning the chart and choosing chart type
Set co = ActiveSheet.Shapes.AddChart(xlXYScatter, rngChart.Cells(1).Left, rngChart.Cells(1).Top, rngChart.Width, rngChart.Height)
Set cht = co.Chart
Set sc = cht.SeriesCollection
'Remove any default series
Do While sc.Count > 0
sc(1).Delete
Loop
'Setting chart data
'Graphing Data
With cht.SeriesCollection.NewSeries
.Name = Worksheets("Transposed Data").Cells(3, 1)
.XValues = Worksheets("Transposed Data").Range(Cells(2, 5), Cells(2, BinNumber + 4))
.Values = Worksheets("Transposed Data").Range(Cells(3, 5), Cells(3, BinNumber + 4))
.MarkerSize = 4
.MarkerStyle = xlMarkerStyleCircle
End With
'Setting chart labels
With cht
.HasTitle = True
.ChartTitle.Characters.Text = "Counts per energy level"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Energy (keV)"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Counts"
.Axes(xlCategory).HasMajorGridlines = True
.Axes(xlCategory).HasMinorGridlines = True
End With
The code stops when it tries to set the x and y values under the Graphing Data header.
Just to single it out, I'll include it again below.
'Graphing Data
With cht.SeriesCollection.NewSeries
.Name = Worksheets("Transposed Data").Cells(3, 1)
.XValues = Worksheets("Transposed Data").Range(Cells(2, 5), Cells(2, BinNumber + 4))
.Values = Worksheets("Transposed Data").Range(Cells(3, 5), Cells(3, BinNumber + 4))
.MarkerSize = 4
.MarkerStyle = xlMarkerStyleCircle
The data for the x-values is in range E2 to BZX2 and the data for the y-values is in range E3 to BZX3. Cell A3 just has the title for the chart.