excel - VBA 搜索文本框和填充列表框
问题描述
嗨,我有用户表单,我可以在文本框中输入项目的条形码和描述,它会显示结果...但是在我的代码中我只能搜索第一列...我希望工作表中的所有列都可以搜索在文本框中我有 8 列
Private Sub TextBox1_Change()
Me.TextBox1.text = StrConv(Me.TextBox1.text, vbProperCase)
Dim i As Long
Me.ListBox1.Clear
On Error Resume Next
For i = 1 To Application.WorksheetFunction.CountA(Sheet1.Range("A:A"))
a = Len(Me.TextBox1.text)
If Left(Sheet1.Cells(i, 1).text, a) = Left(Me.TextBox1.text, a) Then
Me.ListBox1.AddItem Sheet1.Cells(i, 1).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 2) = Sheet1.Cells(i, 3).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 3) = Sheet1.Cells(i, 4).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 4) = Sheet1.Cells(i, 5).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 5) = Sheet1.Cells(i, 6).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 6) = Sheet1.Cells(i, 7).Value
Me.ListBox1.List(ListBox1.ListCount - 1, 7) = Sheet1.Cells(i, 8).Value
End If
Next i
End Sub
解决方案
更快地尝试此代码...
Private Sub TextBox1_Change()
Dim myArray, lr, x, i
Dim DATA As Worksheet
Set DATA = Worksheets("Sheet1")
lr = DATA.Cells(Rows.Count, 1).End(xlUp).Row
ListBox1.Clear
If TextBox1.Text = "" Then Exit Sub
myArray = DATA.Range("A2:H" & lr + 1)
ReDim y(1 To UBound(myArray) * 8, 1 To 8)
For i = LBound(myArray) To UBound(myArray)
a = Len(Me.TextBox1.Text)
For x = 1 To 8
If Left(myArray(i, x), a) = Left(TextBox1.Text, a) Then
rw = rw + 1
For yy = 1 To 8
y(rw, yy) = myArray(i, yy)
Next yy
End If
Next
Next i
If rw > 0 Then
ListBox1.List = y()
End If
End Sub
但是一次搜索所有列需要时间,但这里的想法
推荐阅读
- image - 网页无法显示某些图像
- c++ - C++ 用 rand 定义函数语法
- javascript - NightmareJs + Jquery 返回空的 JSON 响应
- python - 一组 Python 字典是否适合处理一小组快速变化的值?
- list - Prolog 创建列表
- python - Python:如何将对象转换为整数
- rabbitmq - rabbitmqctl 中的 CTL 代表什么?
- python - 如何在 Python 中引用另一个类变量来初始化一个类变量?
- javascript - 如何在javascript中将字符串用作具有不同参数的对象?
- r - R中每列中缺失值的数量