'Creating charts based on user choice using user form and vba excel
I manage to get my desired user form based on the selected data range with the following code below:
Private Sub UserForm_Activate()
Dim rng As Range
Dim ctl As Control
Set rng = Selection
For i = 1 To rng.Columns.Count - 1
Set ctl = Me.Controls.Add("forms.label.1")
With ctl
.Name = "Series" & i + 1
.Caption = rng.Cells(1, 1 + i)
.Top = 15 + (i * 35)
.Left = 24
.TextAlign = 2
.Width = 126
.Height = 12
End With
Next i
For i = 1 To rng.Columns.Count - 1
Set ctl = Me.Controls.Add("forms.combobox.1")
With ctl
.Name = "ComboBox" & i + 1
.Top = 15 + (i * 35)
.Left = 216
.TextAlign = 2
.Width = 174
.Height = 15
.AddItem "Clustered Column"
.AddItem "Stacked Column"
.AddItem "Line"
.AddItem "Stacked Line"
End With
Next i
End Sub
But the issue is I can't seem to get my desired chart based on the choice made in the user form with this following codes:
Private Sub CommandButton1_Click()
Dim rng As Range
Set rng = Selection
Dim cht As Chart
Set cht = ActiveChart
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
With cht
If cht.ComboBox2 = "Clustered Column" Then
cht.FullSeriesCollection(1).ChartType = xlColumnClustered
ElseIf ComboBox2 = "Stacked Column" Then
cht.FullSeriesCollection(1).ChartType = xlColumnStacked
ElseIf ComboBox2 = "Line" Then
cht.FullSeriesCollection(1).ChartType = xlLine
ElseIf ComboBox2 = "Stacked Line" Then
cht.FullSeriesCollection(1).ChartType = xlLineStacked
End If
End With
With cht
If ComboBox3 = "Clustered Column" Then
cht.FullSeriesCollection(2).ChartType = xlColumnClustered
ElseIf ComboBox3 = "Stacked Column" Then
cht.FullSeriesCollection(2).ChartType = xlColumnStacked
ElseIf ComboBox3 = "Line" Then
cht.FullSeriesCollection(2).ChartType = xlLine
ElseIf ComboBox3 = "Stacked Line" Then
cht.FullSeriesCollection(2).ChartType = xlLineStacked
End If
End With
With cht
If ComboBox4 = "Clustered Column" Then
cht.FullSeriesCollection(3).ChartType = xlColumnClustered
ElseIf ComboBox4 = "Stacked Column" Then
cht.FullSeriesCollection(3).ChartType = xlColumnStacked
ElseIf ComboBox4 = "Line" Then
cht.FullSeriesCollection(3).ChartType = xlLine
ElseIf ComboBox4 = "Stacked Line" Then
cht.FullSeriesCollection(3).ChartType = xlLineStacked
End If
End With
Unload Me
End Sub
I've tried userform1.combobox2.value also can't seem to do the trick. I think it is probably because my combobox name is wrong? But I can't seem to find the name of my combobox since it is only available only if I run the 1st port of the code.
Here is an example of the data I would like to chart it into stacked columns for police and doctor and line for total.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

