禁用或隐藏组合框中的选项 VBA Excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19402747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:51:07  来源:igfitidea点击:

Disable or hide options in combo box VBA Excel

excel-vbavbaexcel

提问by Geovanni Petty

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!

我在由用户组类型组成的 Excel 用户窗体中有一个组合框。根据用户访问级别,我希望禁用某些 Option\item 或不可见。 我不想使用 Removeitem,因为我每次都必须重新填充列表!

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\grayedout or not visible but still in the Combobox list!*

我只是希望它被禁用\变灰或不可见,但仍在组合框列表中!*

回答by Siddharth Rout

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.

AFAIK,你不能这样做,但有另一种选择。用户将无法选择某些项目(无论您指定哪个),即使它是可见的且未被禁用。

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

当您选择第 2、3 或 4 项时,您将获得 Please Choose Again

enter image description here

在此处输入图片说明