Vba 将列表框作为对象进行操作

Vba 将列表框作为对象进行操作,vba,Vba,我正在开发一个包含列表框的VBA用户表单。 到目前为止,当我不得不操纵一个或多个时,我总是在我的潜艇中这样进行,以dlg作为对话框名称,它不会带来任何问题,因为我从不想做任何复杂的事情: Dim List1 As Object ... List1 = dlg.GetControl("CBXname") ... List1.addItem("String",index) ... 现在,我想在本小节中执行以下操作 ... If (List1.Exists(Cell1.String) = False

我正在开发一个包含列表框的VBA用户表单。 到目前为止,当我不得不操纵一个或多个时,我总是在我的潜艇中这样进行,以dlg作为对话框名称,它不会带来任何问题,因为我从不想做任何复杂的事情:

Dim List1 As Object
...
List1 = dlg.GetControl("CBXname")
...
List1.addItem("String",index)
...
现在,我想在本小节中执行以下操作

...
If (List1.Exists(Cell1.String) = False) Then
    List1.addItem(Cell1.String,k)
End If
...
List1.Clear
...

但我两者都不能做,因为List1是一个对象。但是,如果我决定将List1声明为Listbox,我不知道如何从对话框中获取Listbox上的适当控件。当前getcontrol给了我一个错误。

代码的一个问题是Listbox对象没有exists属性。要检查listbox项中是否已经存在值,您需要遍历这些项

dim i as integer 
for i = 0 to List1.listcount - 1 
    if List1.column(0, i) = myvalue then 
        'myvalue exists in List1, skip
    else
        List1.additem myvalue     
    end if 
next i
其中myvalue是您试图添加到列表框中的任何值。但这就引出了代码中的第二个问题,即添加Cell1.String。如果试图从工作表范围添加值,则需要引用该范围的值,因为此处使用的工作表范围没有字符串属性。即,单元格1=范围A1.0


至于获取列表框的控制权,您可以简单地将对象名称引用为表单的对象。例如,dlg.List1,如果对象的名称是List1。

这里有一个通用例程,您可以为任何列表框调用它。调用代码假定一个名为ListBox1的列表框、一个名为TextBox1的文本框和一个名为CommandButton的命令按钮。单击按钮时,它会在列表框中搜索textbox1中的文本

Private Function ExistsInListbox(ByRef aListBox As msforms.ListBox, ByVal Item As String) As Boolean

Dim booFound As Boolean
    booFound = False
    Dim t As Integer
    ExistsInListbox = False
    For t = 0 To aListBox.ListCount - 1 'correction, aListBox not ListBox1
    If Item = aListBox.List(t) Then
            'if we find a match, short-circuit the loop
            booFound = True
            Exit For
        End If
    Next

   ExistsInListbox = booFound
End Function
private sub CommandButton_click()
 Dim answer As String
    Dim val As Boolean
    val = ExistsInListbox(Me.ListBox1, TextBox1.Text)
    If val Then
        answer = "found"
    Else
        answer = "Not Found"
    End If
    MsgBox "found-" & answer
End Sub