I am writing a script in Excel VBA where I am working in a Userform
. In this Userform
, I have two ComboBox
, ComboBox1
and ComboBox4
. Both ComboBox
are a drop-down list that is populated in the script.
I have made it so that ComboBox4
gets populated after and depending on the user input on ComboBox1
. I have written the following code:
Private Sub UserForm_Activate()
With ComboBox1
.AddItem "Afghanistan"
.AddItem "Åland Islands"
.AddItem "Albania"
.AddItem "Algeria"
.AddItem "American Samoa"
.AddItem "Andorra"
End With
With ComboBox4
.AddItem "Africa"
.AddItem "Americas"
.AddItem "Asia"
.AddItem "Europe"
.AddItem "MENA"
.AddItem "Other"
End With
End Sub
Private Sub ComboBox1_Change()
If ComboBox1 = "" Then
ComboBox4 = vbNullString: ComboBox4.Enabled = True
Else
Dim index As Integer
index = ComboBox1.ListIndex
Select Case index
Case Is = 0
ComboBox4.Value = "Asia"
ComboBox4.Enabled = False
Case Is = 1
ComboBox4.Value = "Europe"
ComboBox4.Enabled = False
Case Is = 2
ComboBox4.Value = "Europe"
ComboBox4.Enabled = False
Case Is = 3
ComboBox4.Value = "MENA"
ComboBox4.Enabled = False
Case Is = 4
ComboBox4.Value = "Asia"
ComboBox4.Enabled = False
Case Is = 5
ComboBox4.Value = "Europe"
ComboBox4.Enabled = False
End Select
End If
End Sub
Everything seems to be working fine. The only thig is that ComboBox1
has a strange and annoying behaviour: Whenever I open the Userform
and select an option from the drop-down list of ComboBox1
or start typing on it it doesn't select the option or type the letter unless I do it twice. So, if I select an option from the list, it remains blank until I select it again; if I start typing, the first letter I typed never appears, just those from the second on.
I don't understand what is going on and have researched on it, albeit unsuccessfully. Thank you for the help!
使用ComboBox1_AfterUpdate()
事件代替ComboBox1_Change()
事件
in your narrative you're telling about ComboBox1
and CombBox2
, while your code shows ComboBox1
and CombBox4
just check you're not messing things up
then, maybe you have some ComboBox2_Change
(or ComboBox4_Change
) that alters your code ComboBox1
value and thus interfere with ComboBox1_Change
BTW you may adopt a shorter code for ComboBox1_Change
, like follows:
Private Sub ComboBox1_Change()
If ComboBox1 = "" Then
ComboBox4 = vbNullString: ComboBox4.Enabled = True
Else
ComboBox4.Enabled = False
Select Case ComboBox1.ListIndex
Case 0, 4
ComboBox4.Value = "Asia"
Case 1, 2, 5
ComboBox4.Value = "Europe"
Case 3
ComboBox4.Value = "MENA"
Case Else
ComboBox4.Enabled = True
End Select
End If
End Sub
where you would change all ComboBox4
occurrences to ComboBox2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.