arrays - 如何使用用户输入在 VBA 中创建过滤器/下拉菜单
问题描述
目前我的代码提示用户输入一个逗号分隔的标题列表。但是,有没有办法我可以更改代码,以便用户可以从下拉菜单中搜索所需的标题,单击标题旁边的复选框,并能够继续搜索所需的标题,直到完成。并将这些字符串存储在一个数组中。
Dim arWords() As String
myt = InputBox("Enter User Input")
arWords() = Split(myt, ",")
For X = 0 To UBound(arWords)
myf = myf & arWords(X) & vbNewLine
Next X
我稍后在代码中有一个数组(arrH),其中存储了所有标题,所以我认为 id 必须使用它作为源,如果我需要一个?或者我相信。我还在学习。
arrH = Split(arrTxt(HeaderRow), vbTab)
谢谢!
解决方案
创建一个用户窗体。
“用户可以从下拉菜单中搜索所需的标题,单击标题旁边的复选框,并能够继续搜索所需的标题,直到完成”。
带有组合框和复选框的用户窗体。在 CheckBox_Change 事件中,让脚本将 ComboBox 的值存储到公共模块级数组并迭代数组索引。
有一个隐藏用户窗体的“完成”按钮。
下面是 Userform 代码模块的样子:
Public SelectedTitles As Variant, ArrCount As Long, EnableEvents As Boolean
Private Sub CheckBox1_Change()
'User has indicated they want to add the currently selected item to the list
If Not EnableEvents Then Exit Sub
If ArrCount = 0 Then 'First item, create the array
SelectedTitles = Array("")
Else
ReDim Preserve SelectedTitles(UBound(SelectedTitles) + 1) 'Next items, add one more space in the array
End If
'Add the selected title to the array
SelectedTitles(ArrCount) = ComboBox1.Value
'Increment the counter
ArrCount = ArrCount + 1
'Reset the checkbox and the combobox
EnableEvents = False
CheckBox1.Value = False
ComboBox1.Value = ""
EnableEvents = True
End Sub
Private Sub CommandButton1_Click()
'Done Button
Me.Hide
End Sub
Private Sub UserForm_Initialize()
EnableEvents = True
End Sub
这是一个帮助将项目添加到 ComboBox 列表的子项:
Sub ComboBox_AddFromArray(ByRef ComboBox As Object, ListArray As Variant)
ComboBox.Clear
If IsArray(ListArray) Then
Dim i As Long
For i = LBound(ListArray) To UBound(ListArray)
ComboBox.AddItem ListArray(i), ComboBox.ListCount
Next i
Else
ComboBox.AddItem ListArray, 0
End If
End Sub
这个函数会在之后Load UserForm1
和之前UserForm1.Show
。你会输入像ComboBox_AddFromArray UserForm1.ComboBox1, arrH
.
您将这一切放在一起的方式是拥有一个控制函数,该函数执行所有 Userform 进程,然后返回您需要的内容,即用户选择的标题数组。
这就是它的样子
Function UserInputForm(ByRef ArrayOfAllTitles As Variant) As Variant
Load UserForm1
ComboBox_AddFromArray UserForm1.ComboBox1, ArrayOfAllTitles
UserForm1.Show
UserInputForm = UserForm1.SelectedTitles
Unload UserForm1
End Function
最后,一个如何将该函数包含到您的主子中的示例:
Dim SelectedTitles As Variant
SelectedTitles = UserInputForm(arrH)
'SelectedTitles is now an array of Variant/String values
Dim i As Long
For i = LBound(SelectedTitles) To UBound(SelectedTitles)
Debug.Print SelectedTitles(i)
'Access individual members of the array using SelectedTitles(i)
Next i
推荐阅读
- javascript - discord.js (node:9852) UnhandledPromiseRejectionWarning: ReferenceError: msg is not defined
- c# - 为什么我为检索 DataGridView 的二级属性而执行的自定义 TypeDescriptor 不起作用?
- postgresql - Postgres 在所有字段的开头和结尾添加一个空格
- azureservicebus - Azure 服务总线上的“辅助连接字符串”的用途是什么?
- notifications - OneM2M:通知 IN-CSE 在 MN-CSE 上创建的新资源
- json - 可选+可空值的Gson反序列化
- c++ - Armadillo C++ 配置检查
- python - fast_executemany=True 等效于 SQLALCHEMY 中的 Oracle
- java - 为什么我们不能只抛出 Exception/Throwable 而不是有多个异常
- pytorch - 使用卷积自动编码器在照片上添加微笑的问题