【发布时间】:2020-11-13 10:01:29
【问题描述】:
我想在用户窗体的列表框中实现搜索功能,以便更好地查看许多列,但遗憾的是我找不到解决方案。
最佳解决方案是,如果我可以在文本框中搜索任何行内容(最多 12 列包含诸如姓名、ID、职位、组织等数据)并且列表框会自动更新显示所有匹配条目。
在UserForm_Initialize中我填写了如下列表框:
Private Sub UserForm_Initialize()
With UserForm1
.StartUpPosition = 1
.Top = 1
.Left = 1
End With
Dim last As Integer
last = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row + 1
ListBox1.ColumnCount = 12
ListBox1.ColumnHeads = True
ListBox1.ColumnWidths = "30;50;200;60;30;110;110;90;50;40;50;80;60"
ListBox1.RowSource = "A2:M" & last
End Sub
我想象搜索功能根据Textbox1 中的输入过滤列表框。
经过长时间的研究和考虑(不幸的是,我是一个绝对的 vba 业余爱好者),创建了以下代码:
Private Sub TextBox1_Change()
Dim i As Long
On Error Resume Next
Me.TextBox1.Text = StrConv(Me.TextBox1.Text, vbProperCase)
Me.ListBox1.Clear
For i = 2 To Application.WorksheetFunction.CountA(ActiveSheet.Range("A:A"))
For x = 1 To 12
a = Len(Me.TextBox1.Text)
If Left(ActiveSheet.Cells(i, x).Value, a) = Me.TextBox1.Text And Me.TextBox1.Text <> "" Then
Me.ListBox1.AddItem ActiveSheet.Cells(i, x).Value
For c = 1 To 12
Me.ListBox1.List(ListBox1.ListCount - 1, c) = ActiveSheet.Cells(i, c + 1).Value
Next c
End If
Next x
Next i
End Sub
我的问题:是否有人有更智能/更精简的解决方案,或者可以帮助我的代码正常运行,因为目前我在执行时收到了runtime error '9'。
【问题讨论】:
-
发布了您的列表框问题的解决方案,展示了如何处理您的问题的总体视图。 - 如果有帮助,请随意勾选绿色复选标记接受 :-) 仅供参考 相关链接(数组方法)How to speed up filling of listbox values on UserForm 和 Populate ListBox with multiple columns
标签: excel vba listbox userform