我在用户表单上使用了一个组合框,并通过使用字典(来自Range)向其添加了一个列表。
我需要组合框显示部分字符串匹配,因为我输入到它,所以我已经使用了这个代码:
With Me.ComboBox1
.List = Filter(dic.Keys, .Text, True, vbTextCompare)
.DropDown 'Expand filter selection (reduced number of valid elements)
End With
上面的代码工作,因为它应该,
但是,如果我选择任何项目(使用下拉箭头在组合框本身),那么我不能列出组合框,我必须关闭用户表单,并再次打开。
如果我注释了这行代码,问题就消失了,但是我丢失了部分字符串匹配。
.List = Filter(dic.Keys, .Text, True, vbTextCompare)
这是我的完整代码:Private Sub ComboBox1_Change()
If ComboBox1.value <> "False" And ComboBox1.value <> "" Then
'Partial String Match
With Me.ComboBox1
.List = Filter(dic.Keys, .Text, True, vbTextCompare) 'The issue on this line
.DropDown 'Expand filter selection (reduced number of valid elements)
End With
End If
End Sub
一如既往,感谢您对我的帮助。
请尝试下一种方式:
- 在表单代码模块的顶部(在declarations区域)创建下一个全局变量:
Private dict As Scripting.Dictionary
Private noEvents As Boolean, boolNot As Boolean
- 使用过的字典应该在以下代码事件之前加载。可能,在
UserFor_Initialize
事件中。我想你的代码已经做到了。
请复制下一个事件代码,而不是您的:
Private Sub ComboBox1_Change()
Dim chNo As Long, arr, chVar As String, mtch
If ComboBox1.Value <> "False" And ComboBox1.Value <> "" Then
If Not noEvents Then
With Me.ComboBox1
arr = filter(dict.Keys, .Text, True, vbTextCompare) 'place the filtered dict.keys in an array
mtch = Application.match(.Text, dict.Keys, 0) 'check if the combo value is A (whole) DICTIONARY KEY
'or PART OF IT
If IsError(mtch) Then 'if part of the key:
.List = arr 'load combo with filtered array
.DropDown 'Expand filter selection (reduced number of valid elements)
noEvents = True: boolNot = True 'make boolean variables True
Else 'if the whole key:
.List = dict.Keys: noEvents = False: boolNot = False 'load the dict keys and make bool vars False
End If
End With
Else
If Not boolNot Then
Me.ComboBox1.List = dict.Keys 'place the whole dict keys array
boolNot = True 'not letting next time do do the same
Else
boolNot = False 'reinitialize bool variable
End If
noEvents = False 'reinitialize bool variable
End If
Else
Me.cbE.List = dict.Keys 'when clearing combo value (nothing has been revealed by filterring, for instance)
End If
End Sub
注意,我没有使用dic
变量的字典,我使用dict
…
请在测试后发送一些反馈。我没有深入测试,但我认为它应该做(我理解)你需要的……