Combobox选择未出现在第一次单击Excel VBA中



我正在在 Userform中工作的excel VBA编写脚本。在此Userform中,我有两个ComboBoxComboBox1ComboBox4。两个ComboBox都是脚本中填充的下拉列表。

我已经做到了,以便ComboBox4ComboBox1上的用户输入之后被填充并具体。我编写了以下代码:

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

一切似乎都很好。唯一的thig是ComboBox1具有奇怪而烦人的行为:每当我打开Userform并从ComboBox1的下拉列表中选择一个选项或开始在其上键入它,它不会选择该选项或输入字母,除非我这样做两次。因此,如果我从列表中选择一个选项,它将保持空白,直到我再次选择它。如果我开始键入,我输入的第一个字母永远不会出现,只是第二个字母。

我不明白发生了什么,尽管没有成功。谢谢您的帮助!

使用ComboBox1_AfterUpdate()事件而不是ComboBox1_Change()事件

在您的叙述中,您正在讲述有关ComboBox1CombBox2的讲述,而代码显示ComboBox1CombBox4

只检查你不是把事情弄乱

然后,也许您有一些ComboBox2_Change(或ComboBox4_Change),可以改变您的代码ComboBox1值,从而干扰ComboBox1_Change

顺便说一句,您可以采用ComboBox1_Change的较短代码,如下:

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

在哪里将所有ComboBox4的出现更改为ComboBox2

相关内容

  • 没有找到相关文章

最新更新