簡體   English   中英

使用 VBA Excel 進行高級搜索

[英]Advanced search using VBA Excel

我有一個數據列表(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

如評論中所述,您可以像這樣使用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

一種更快的方法是將所有內容存儲在一個數組中並循環遍歷它。 然而,當我開始時,我發現使用較少抽象的方法和逐步學習更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM