Disable or hide options in combo box VBA Excel

2019-08-05 21:44发布

I have a combo box in a Excel Userform that consist of User Group Types. Depending on the user access level, I would like to have some Option\item disable or not visible. I don't want to use Removeitem, Because I would have to repopulate the list every time!

sub ComboBox_Enter() 

accessLvl = 1

ComboBox.AddItem "0-Show"
ComboBox.AddItem "1-Hide or disable"
ComboBox.AddItem "2-Show"
ComboBox.AddItem "3-Show"

For i = 0 To 3
      if accessLvl = 1 Then ComboBox.List(1).Hidden = True ' This not does work!! ''
Next

End sub

I just want it to be disabled\grayed out or not visible but still in the Combobox list!*

1条回答
贪生不怕死
2楼-- · 2019-08-05 22:25

AFAIK, you can't do that but there is an alternative. The user will not be able to select certain items (whichever you specify) even though it will be visible and not disabled.

For this try this code

Dim boolC As Boolean

'~~> Add Sample data
Private Sub UserForm_Initialize()
    ComboBox1.AddItem "Please Choose Again"

    For i = 1 To 10
        ComboBox1.AddItem i
    Next i
End Sub

'~~> This will not let the user select items in 2nd
'~~> 3rd and 4th items
Private Sub ComboBox1_Change()
    If Not boolC Then
        boolC = True
        Select Case ComboBox1.ListIndex
            Case 1, 2, 3: ComboBox1.ListIndex = 0
        End Select
        boolC = False
    End If
End Sub

Screenshot

Let's say your form looks like this on form start up.

enter image description here

The moment you select the 2nd ,3rd or the 4th item, you will get Please Choose Again

enter image description here

查看更多
登录 后发表回答