Hi,
I have to plot multiple charts having multiple data series (8 or 9 X-Y). I am able to plot one single chart for a defined range, for which the vb macro code is pasted below. What I really want to do is to make this range selection (columns) dynamic. For example for the fist chart I select the range
, but I don't know how to select several multiple ranges (for e.g.
and so on to create multiple charts from the data in the same worksheet? I am really new to VB coding. I desperately need help. The macro code is:
Sub NormDistPlot()
Dim rngDataSource As range, mybook As Workbook, ws As Worksheet
Dim iDataRowsCt As Long
Dim iDataColsCt As Integer
Dim iSrsIx As Integer
Dim chtChart As Chart
Dim srsNew As Series
Workbooks.Open "C:\data2\sample.xlsx"
Set mybook = ActiveWorkbook
Set ws = mybook.ActiveSheet
For Each ws In mybook.Worksheets
range("B1:Q15").Select
If Not TypeName(Selection) = "Range" Then
'' Doesn't work if no range is selected
MsgBox "Please select a data range and try again.", _
vbExclamation, "No Range Selected"
Else
Set rngDataSource = Selection
With rngDataSource
iDataRowsCt = .Rows.Count
iDataColsCt = .Columns.Count
End With
If iDataColsCt Mod 2 > 0 Then
MsgBox "Select a range with an EVEN number of columns.", _
vbExclamation, "Select Even Number of Columns"
Exit Sub
End If
'' Create the chart
Set chtChart = ActiveSheet.ChartObjects.Add( _
Left:=ActiveSheet.Columns(ActiveWindow.ScrollColumn).Left + _
ActiveWindow.Width / 4, _
Width:=ActiveWindow.Width / 2, _
Top:=ActiveSheet.Rows(ActiveWindow.ScrollRow).Top + _
ActiveWindow.Height / 4, _
Height:=ActiveWindow.Height / 2).Chart
With chtChart
.ChartType = xlXYScatterLines
'' Remove any series created with the chart
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
For iSrsIx = 1 To iDataColsCt - 1 Step 2
'' Add each series
Set srsNew = .SeriesCollection.NewSeries
With srsNew
.Name = rngDataSource.Cells(1, iSrsIx)
.Values = rngDataSource.Cells(2, iSrsIx + 1) _
.Resize(iDataRowsCt - 1, 1)
.XValues = rngDataSource.Cells(2, iSrsIx) _
.Resize(iDataRowsCt - 1, 1)
End With
Next
End With
End If
Next ws
End Sub
I acquired this code thanks to the hyper informative page: http://peltiertech.com/Excel/ChartsH...html#manyxoney
The sample excel file is here: Sample.xlsx
I hope to be able to solve this at the soonest.
Thanks in advance,
Sanjeev
Bookmarks