使用VBA Excel进行高级搜索

问题描述 投票:0回答:2

我有一个数据列表(20,000多种产品),根据产品的状况有不同的定价,用户需要能够快速查询某些等级的产品定价,我当前的挑战是用户经常使用vlookup的失败只会进行关键字搜索,而没有确切的说明。我想使用vlookup保留现有的查找,因为当用户拥有确切的产品标题时,它仍将是一种快速搜索,但是当他们只有一个关键字时,我想添加一个高级搜索(我尝试过数据验证可搜索列表,但它们是缓慢且不可靠)

我已经创建了一个列表框,但无法获取代码来搜索我的数据集,然后显示结果,

这是我正在使用的代码(库存数据包含我所有的产品和价格,第二页称为搜索,我希望用户在其中查找所需的内容

enter code here

Private Sub cmdsearch_click()

Dim Rownum As Long
Dim Searchrow As Long

Rownum = 2
Searchrow = 2

Worksheets("Stock Data").Activate

Do Until Cells(Rownum, 1).Value = ""
If InStr(1, Cells(Rownum, 1).Value, txtkeywords.Value, vbTextCompare) > 0 Then
   Worksheets("Sheet1").Cells(Searchrow, 1).Value = Cells(rownnum, 1).Value
   Worksheets("Sheet1").Cells(Searchrow, 2).Value = Cells(rownnum, 2).Value
   Worksheets("Sheet1").Cells(Searchrow, 3).Value = Cells(rownnum, 3).Value
   Searchrow = Searchrow + 1
End If
Rownum = Rownum + 1



Loop

If Searchrow = 2 Then
MsgBox "Sorry No products found, please request a price"
End If

Lstsearchresults.RowSource = "SearchResults"

End Sub
excel database vba search listbox
2个回答
0
投票

如评论中所述,您可以像这样使用Range.Find

Private Sub cmdsearch_click()

Dim rowResult As Long
Dim strSearch As String

rowResult = 2
strSearch = txtkeywords.Value

Dim rowLast As Long
rowLast = Worksheets("Stock Data").Cells(Rows.Count, 1).End(xlUp).Row

Dim rngFound As Range
Dim firstAdress As String

With Worksheets("Stock Data").Range("A1:A" & rowLast)
    Set rngFound = .Find(strSearch, LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False)
    If Not rngFound Is Nothing Then

        firstAddress = rngFound.Address
        Do
            Worksheets("Sheet1").Cells(rowResult , 1).Value2 = rngFound.Value2
            Worksheets("Sheet1").Cells(rowResult , 2).Value2 = rngFound.Offset(0, 1).Value2
            Worksheets("Sheet1").Cells(rowResult , 3).Value2 = rngFound.Offset(0, 2).Value2
            rowResult = rowResult + 1

            Set rngFound = .FindNext
        Loop While rngFound.Address <> firstAdress

    Else
        MsgBox "Sorry No products found, please request a price"
    End If
End With

Lstsearchresults.RowSource = "SearchResults"

End Sub

一种更快的方法是将所有内容存储在数组中并循环遍历。但是,当我起步时,我发现使用较少的抽象方法并逐步学习变得更容易。

© www.soinside.com 2019 - 2024. All rights reserved.