I am relatively new to VBA. I am attempting to automate the generation of a graph containing Beta values using the following steps:
Step 1 - Generate a list of random numbers in Column A
Step 2 - Based on values in Column A, apply the Beta.Dist formula in Column B
Step 3 - Generate a scatterplot based on values in Column B, the scatterplot should look like a U-shaped distribution curve
I've tried using the following code but I am only seeing 1 value in the scatter plot (i.e., the scatterplot only has one dot).
Here's the code:
Option Explicit
Option Base 1
Sub Macro1()
Application.ScreenUpdating = False
Dim i%, j%
Range("A1").Select
Selection = "0.99"
Selection.Offset(0, 1) = "Beta(" & Selection & ", " & Selection & ") Density"
For i = 1 To 301
Selection.Offset(i, 0).Formula = "= rand()"
Selection.Offset(i, 1).Formula = "=BETA.DIST(A2:A302,0.99,0.99,False)"
Next i
j = ActiveSheet.ChartObjects.Count
ActiveSheet.Shapes.AddChart2(-1, xlXYScatter, 98 + j * 10, 16.5 + j * 10, 319, 296.5).Select
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("B2:B302")
ActiveSheet.ChartObjects(j + 1).Activate
ActiveChart.SetElement (msoElementChartTitleAboveChart)
Selection.Caption = "="
ActiveChart.Axes(xlCategory).MaximumScale = 1
ActiveChart.Axes(xlCategory).Format.Line.Visible = msoFalse
ActiveChart.Axes(xlCategory).MajorGridlines.Delete
ActiveChart.Axes(xlValue).MaximumScale = 1.1
ActiveChart.Axes(xlValue).TickLabels.NumberFormat = "0.000#"
ActiveChart.Axes(xlValue).Format.Line.Visible = msoFalse
ActiveChart.Axes(xlValue).MajorGridlines.Delete
Range("E1") = ""
Range("I1") = ""
Range("B1").Select
Application.ScreenUpdating = True
End Sub
I'm hoping to get a U-shaped beta distribution curve in the scatter plot. Appreciate any form of help and thank you in advance!
You're not setting the chart data correctly:
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("A2:B302")
Related
I'm trying to generate scatter plot from 2 data-columns, but instead I get a line plot where data of the first column is ignored (i.e.: if I have 1000 points, on x-axis I see values from 1 to 1000, regardless of the data stored in 1st column). I can't find the error in my code. What's wrong?
Public Sub Graph_Refresh()
Dim cht As Chart
Dim i As Integer
Dim seriesIndex As Integer
Set cht = Sheets("Graph").ChartObjects("Chart 1").Chart
seriesIndex = 0
' ***** CLEAR OLD CONTENT *****
cht.ChartArea.ClearContents
' ***** NON CHANGEABLE PARAMETERS *****
'Format Font Type and Size
cht.ChartType = xlXYScatterLinesNoMarkers ' scatter plot
cht.ChartArea.Format.TextFrame2.TextRange.Font.Name = "Arial"
cht.ChartArea.Format.TextFrame2.TextRange.Font.Size = 12
cht.HasTitle = False ' No chart title
'cht.SetElement (msoElementPrimaryValueGridLinesMajor) 'Gridlines
'Adjust x-axis
cht.HasAxis(xlCategory, xlPrimary) = True
cht.Axes(xlCategory, xlPrimary).HasTitle = True
cht.Axes(xlCategory).AxisTitle.Text = "Frequency [MHz]"
cht.Axes(xlCategory).MinimumScale = Sheets("Graph").Range("AI7").Value
cht.Axes(xlCategory).MaximumScale = Sheets("Graph").Range("AI8").Value
'Adjust y-axis
cht.HasAxis(xlValue, xlPrimary) = True
cht.Axes(xlValue, xlPrimary).HasTitle = True
cht.Axes(xlValue).AxisTitle.Text = "S-Parameters [dB]"
cht.Axes(xlValue).MinimumScale = Sheets("Graph").Range("AI9").Value
cht.Axes(xlValue).MaximumScale = Sheets("Graph").Range("AI10").Value
cht.Axes(xlValue).CrossesAt = -100
' Data Series
For i = 1 To 5
seriesIndex = seriesIndex + 1
cht.SeriesCollection.NewSeries
With Sheets("Graph")
cht.SeriesCollection(seriesIndex).Name = .Cells(6 + (i - 1) * 4).Value & " S11"
End With
cht.SeriesCollection(seriesIndex).XValues = "='" & Sheets("Data" & CStr(i)).Name & "'!$K$4:$K$10004"
cht.SeriesCollection(seriesIndex).Values = "='" & Sheets("Data" & CStr(i)).Name & "'!$L$4:$L$10004"
' Set line size and color
With cht.SeriesCollection(seriesIndex)
.Format.Line.Weight = 2.25
.Format.Line.Visible = msoFalse
.Format.Line.Visible = msoTrue
.Format.Line.ForeColor.RGB = RGB(255,0,0)
.MarkerStyle = xlMarkerStyleNone
End With
Next i
' Legend
End Sub
Data are stored in sheets "Data1" - "Data5", and the range should be ok. Chart "Chart 1" already exists (that's why I don't create it).
Thanks in advance for help!
After some more investigation, I fund the answer. I leave it here for anyone who might be interested.
The problem was due to the fact that the data range that I provided included empty cells (or, to be more precise, cells with functions returning blanks).
Resizing XValues and Values to include only cells with data solved the problem.
Hi I want to add customize data label to my bubble chart. my code is below. at the moment data label refer to XValues. I would like my data label fill with bubble size. would u mind help me how I can customize below code?
I tried to add .DataLabel.Text = "txt" but I received below
error:
Run-time error '438':Object doesn't support this property or method
Public Sub CreateMultiSeriesBubbleChart()
If (Selection.Columns.Count <> 4 Or Selection.Rows.Count < 3) Then
MsgBox "Selection must have 4 columns and at least 2 rows"
Exit Sub
End If
Dim red, green, blue As Integer
Dim bubbleChart As ChartObject
Set bubbleChart = ActiveSheet.ChartObjects.Add(Left:=Selection.Left, Width:=600, Top:=Selection.Top, Height:=400)
bubbleChart.Chart.ChartType = xlBubble
Dim r As Integer
For r = 2 To Selection.Rows.Count
With bubbleChart.Chart.SeriesCollection.NewSeries
.Name = "=" & Selection.Cells(r, 1).Address(External:=True)
.XValues = Selection.Cells(r, 2).Address(External:=True)
.Values = Selection.Cells(r, 3).Address(External:=True)
.BubbleSizes = Selection.Cells(r, 4).Address(External:=True)
.Format.Fill.Solid
.Format.Fill.ForeColor.RGB = RGB(61, 161, 161)
' .DataLabel.Text = "txt"
End With
Next
bubbleChart.Chart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
bubbleChart.Chart.Axes(xlCategory, xlPrimary).AxisTitle.Text = "=" & Selection.Cells(1, 2).Address(External:=True)
bubbleChart.Chart.SetElement (msoElementPrimaryValueAxisTitleRotated)
bubbleChart.Chart.Axes(xlValue, xlPrimary).AxisTitle.Text = "=" & Selection.Cells(1, 3).Address(External:=True)
bubbleChart.Chart.SetElement (msoElementPrimaryCategoryGridLinesMajor)
bubbleChart.Chart.Axes(xlCategory).MinimumScale = 0
End Sub
My input sample:
Label Hour Day count
01-SUNDAY 14 1 1
01-SUNDAY 19 1 1
02-MONDAY 12 2 1
02-MONDAY 13 2 1
02-MONDAY 14 2 2
02-MONDAY 16 2 2
Without using VBA, right click on the bubbles and select Add Data Labels. Then, right click on the data labels and click Format Data Labels. Under Label Options, select Value From Cells and specify the cells containing the labels you'd like to use.
DataLabel.Text is a method for a Point, not the NewSeries
This code:
For r = 2 To Selection.Rows.Count
With bubbleChart.Chart.SeriesCollection.NewSeries
[...]
.DataLabel.Text = "txt"
End With
Next
...attempts to label the series, and fails.
Recognizing this code as being from another famous example of "multi-series Bubble Charts", it is a logical assumption that we only need to handle 1 data point per series, which makes the following code the solution:
For r = 2 To Selection.Rows.Count
With bubbleChart.Chart.SeriesCollection.NewSeries
[...]
.Points(1).HasDataLabel = True
.Points(1).DataLabel.Text = "txt"
End With
Next
UPDATE 2:
Trying to define the Variable with the column range in the VBA.
Can anyone guess what's wrong in this code ?
Thanks in advance...
UPDATE 1: I have been successful in generating the chart. Thanks to you guys for the constructive criticism.
I'm a newbie to VBA, just learning :)
My challenge now is to define the row selected for the graph as a variable.
ie. The user gives an input for the ROW and the macro generates the chart for the intended Row.
Find the UPDATED CODE BELOW.
Thanks to all
I need to write a macro to create a individual performance chart in Excel. I have a few lines of code recorded, but the resultant chart does not have any labels on the X & Y Axis.
My requirement is to create a chart with the following features:
Option to choose the row no. in the beginning of the macro (for which row the chart needs to be prepared) - some input box
Comparison Feature to compare Row 1 with Row 2. (some input box)
Data Series Label (X Axis)
Chart Title
MY EXCEL LOOKS LIKE THIS:
Sales Achieved |Clients Met| Client Responsiveness|
Employee 1 | 6 | 7 | 8 |
Employee 2 | 6 | 7 | 8 |
Employee 3 | 6 | 7 | 8 |
Employee 4 | 6 | 7 | 8 |
Sub generatecharts()
Dim xValRange As Range
Dim r
r = irow
irow = InputBox("Which Chart do you want to generate?")
With ActiveSheet
Set xValRange = ActiveSheet.Range("B" & r & ":" & "Q" & r)
End With
With ActiveSheet
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Values = xValRange
ActiveChart.SeriesCollection(1).XValues = "=Sheet2!$B$1:$Q$2"
ActiveChart.SeriesCollection(1).Name = "=Sheet2!$A$" & r
With ActiveChart.Parent
.Height = 400
.Width = 800
End With
End With
End Sub
Sub Macro4()
Dim xValRange As Range
Dim r As Integer
Range("A30").Select 'selected a blank cell on purpose to avoid undefined charts
r = InputBox("Enter the Row Number to generate Chart")
With ActiveSheet
Set xValRange = ActiveSheet.Range("$B$" & r & ":" & "$T$" & r)
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = Cells(r, 1)
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Values = xValRange
ActiveChart.SeriesCollection(1).XValues_
=ActiveSheet.Range("=KRAs!$B$1:$T$2")
ActiveChart.SeriesCollection(1).Name = ActiveSheet.Range("=KRAs!$A$" & r)
ActiveChart.SetElement (msoElementDataLabelInsideEnd) 'to add the data labels
End With
With ActiveChart.Parent
.Height = 400
.Width = 800
.Top = 150 ' reposition
.Left = 200 'reposition
End With
End Sub
I have some code that is supposed to plot multiple series of data to a single chart all from 2 columns (X and Y values) of data. I have it currently set up such that the if statement checks the "ID" that is constant for a single series in another column of data, and will plot a new series once the "ID" changes to signify a new series, and will then plot to the chart.
The code will cycle through, and I can watch it plot each series I want on the chart, however after executing the chart will only have the last of the series in the two columns plotted. I can check the chart afterwards and see the series have been generated, but all of them are dataless aside from the last in the column. Below is my code and I appreciate any comments.
For i = datastart To dataend
If ws1.Cells(i, 3).Value <> ws1.Cells(i + 1, 3).Value Then
Z = i - k + j
t = i - k + 1
With Chart5
.PlotArea.Select
.SeriesCollection.NewSeries
.SeriesCollection(t).Name = ws1.Cells(i, 3).Value
.SeriesCollection(t).XValues = "=Data!$G$" & Z & ":$G$" & i
.SeriesCollection(t).Values = "=Data!$F$" & Z & ":$F$" & i
End With
j = i
Else
k = i
End If
Next i
I am currently at just getting this functioning.
How about this:
' ... some other code
.SeriesCollection.newSeries
t = .SeriesCollection.Count
.SeriesCollection(t).Name = ws1.Cells(i, 3).Value
.SeriesCollection(t).XValues = "=Data!$G$" & z & ":$G$" & i
.SeriesCollection(t).Values = "=Data!$F$" & z & ":$F$" & i
' ... some other code
I want to graph the result of my table in excel. here is the code that I have :
Sub bow()
'
' bow Macro
'
'
Worksheets("Sheet3").Select
tahX = Cells(3, 3).Value + 2
Xval = Offset(A1, 1, 2, 1, 1)
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet3'!$12:$12,'Sheet3'!$10:$10")
ActiveChart.ChartType = xlXYScatter
ActiveChart.SeriesCollection(1).Name = "=""bowe"""
ActiveChart.SeriesCollection(1).XValues = "='Sheet3'!$12:$12"
ActiveChart.SeriesCollection(1).Values = "='Sheet3'!$10:$10"
End Sub
now I want to limit the X-values to the value that is defined in the cell C3. So for example if C3 = 20, I want it to only use the first 20 values in the row number 12. How can I do that ?
Sina ,
I'm not sure what exactly your problem is, but in this line:
ActiveChart.SeriesCollection(1).XValues = "='Sheet3'!$12:$12"
you are specifying row 12 to be plotted.Instead of !$12:$12 you can have !$C$12:$L$12 which will set range from C3 to L12 .If you want to set the row dynamically you can use :
Set mcStartX = Worksheets(1).Cells(12, 3)
startColX = mcStartX.Address()
//we assume that in cell C3 we have specified number of cells to be plotted
toAdd = Cells(3, 3).Value
Set mcEndX = Worksheets().Cells(12, 2 + toAdd)
endColX = mcEndX.Address()
Using this code, and assuming that you have 10 in C3, you will get $C$12 from startColX and $L$12 from endColX.The rest is straight forward you can use following code:
ActiveChart.SeriesCollection(1).XValues = "='Sheet3'!" + startColX + ":" + endColX
I hope that this could be helpful.
Cheers,