Excel VBA – 检查combolist值并添加(如果尚未添加)

不知道如何解释我的问题 – 所以我很抱歉,如果它似乎有点模棱两可。 我似乎有其他的方法,像检查多个combobox等,但没有什么特别涉及到我在找什么,不确定我是否试图做一些不可能的事情。

我想要做的是检查我的combobox,看看是否已经存在一个值,如果没有,并添加它。

工作簿打开并调用UserForm1.show – 这触发了Userform初始化,它设置了一些文本框的默认值(空和设置像autosize等),这个过程很好,在这个过程中我调用了一个个人函数DrpDwn_init – 想法是DrpDwn_init带有检查并在combobox中设置值。 我可以调用的函数,我甚至可以得到它的值,但我不知道如何检查值是否已经存在。

我现在所拥有的是:

Public Function DrpDwn_Init() Dim Templates() As String Templates = Split("Stuff 1*Stuff 2", "*") For i = 0 To UBound(Templates) If Templates(i) <> UserForm1.DrpDwn_Templates.List(i) Then MsgBox "Does Not match" Else MsgBox "Does Match" End If Next i End Function 

也试图使用

 For i = 0 To UBound(Templates) If CStr(Templates(i)) <> UserForm1.DrpDwn_Templates.List(i) Then For i = 0 To UBound(Templates) If Templates(i) <> CStr(UserForm1.DrpDwn_Templates.List(i)) Then For i = 0 To UBound(Templates) If CStr(Templates(i)) <> CStr(UserForm1.DrpDwn_Templates.List(i)) Then 

以及使用“UserForm1.DrpDwn_Templates.ListIndex(i)

我已经尝试了很多方法,有时我得到的唯一的错误是,突然Userform1.show变得不可接受!? 即使我从来不碰这部分代码。 我真的不知道如何遍历数组,检查每个数组索引项,看它是否存在于combobox中,并根据是否是,执行任务。

真的希望在这里的人可以帮助我解决这个问题(顺便说一句,我已经检查了所有我的代码引用function等是正确的,如果我在这里做错别字,我很抱歉。

您没有循环遍历下拉框中的所有项目。 考虑下面的例子

清单1

 Apples Pears 

清单2

 Oranges Apples 

你需要做的检查如下:

 Apples = Oranges (FALSE) Apples = Apples (TRUE) Pears = Oranges (FALSE) Pears = Apples (FALSE) 

所以这里的简单循环就是这样的

 For i = 1 to 2 For j = 1 to 2 if list1(i) = list2(j) then inList = TRUE End if Next j If inList = TRUE then MsgBox "Found in the list" End if Next i 

更新下面的代码应该与单个用户窗体和该用户窗体上的combobox(UserForm1和ComboBox1,分别)

 Sub test() Dim i As Integer, j As Integer Dim inList As Boolean Dim vListItems As Variant, vTestItems As Variant, vItem As Variant vListItems = Array("Apple", "Orange") vTestItems = Array("Pear", "Apple") 'populate ComboBox1 For Each vItem In vListItems UserForm1.ComboBox1.AddItem vItem Next vItem For i = 0 To UBound(vTestItems) inList = False 'check if item is in your dropdown list already For j = 0 To UserForm1.ComboBox1.ListCount - 1 If vTestItems(i) = UserForm1.ComboBox1.List(j) Then inList = True End If Next j 'insert into list if not found If inList = False Then UserForm1.ComboBox1.AddItem vTestItems(i) End If Next i UserForm1.Show End Sub 

我试了这个,我得到它的工作。 不适合你的变体的需求,但让你更接近找出它

 Private Sub UserForm_Activate() ComboBox1.Clear StuffArray(0) = "Stuff" StuffArray(1) = "Another thing" For i = LBound(StuffArray, 1) To UBound(StuffArray, 1) With ComboBox1 .AddItem StuffArray(i) End With Next i Dim Thing As String Thing = ThisWorkbook.Sheets("Sheet3").Range("u9").Value For i = LBound(StuffArray, 1) To UBound(StuffArray, 1) If Thing <> StuffArray(i) Then With ComboBox1 .AddItem Thing End With ElseIf Thing = StuffArray(i) Then End If Next End Sub 

编辑 – 结果它增加了两次的价值,但这是一个简单的修复:P

在这里输入图像描述