【问题标题】:Search a table with multiple criteria - VBA(Excel)搜索具有多个条件的表 - VBA(Excel)
【发布时间】:2017-09-07 03:24:39
【问题描述】:

我一直在尝试构建基于多个条件的搜索实用程序。我当前的代码可帮助我仅根据一个条件进行搜索。

我希望根据 Desc、类别(部分或完整搜索)、价格(例如 >10、

以下是我正在尝试搜索的示例数据,我也包括了预期的结果场景:

完整数据
搜索

SKU Desc    Category    Price
1   Pen UTL 5
2   Pie1    FOOD    15
3   Pie2    FOOD    17
4   Pie3    FOOD    25
5   Pie4    FOOD    30
6   Paper1  UTL 4
7   Paper2  UTL 4.5
8   Paper3  UTL 10
9   Paper4  UTL 12
10  Paper5  UTL 14
11  Calculator1 UTL 50
12  Calculator2 UTL 70
13  Calculator3 UTL 90

这里将非常感谢有人的帮助。我的实际数据将跨越多达 20K 条记录。

下面是当前代码:这里我有要搜索的数据在A4:D17,结果显示在H:K

Option Explicit

Sub finddata()

Dim Catagoryname As String Dim finalrow As Integer Dim i As Integer 'row counter

Sheets("Data").Range("H5:k17").ClearContents Catagoryname = Sheets("Data").Range("J2").Value finalrow = WorksheetFunction.CountA(Range("A:A"))

For i = 5 To finalrow
    If Cells(i, 3) = Catagoryname Then
        Range(Cells(i, 1), Cells(i, 12)).Copy
        Range("H100").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
    End If Next i

End Sub

【问题讨论】:

  • 你已经有什么代码了?将其添加到您的帖子中
  • excel过滤有什么问题?
  • 您可以使用 Userforms 添加一个组合框,该组合框添加没有重复的 Desc 列,然后使用选择的 desc 使用 Dictionary Object 或 .Find 进行搜索,或者只是过滤

标签: excel vba


【解决方案1】:

@Ashwin,这是我用来在超过 11,000 条记录的列表中搜索部分名称的小例程,然后我可以自动筛选类别以缩小列表范围。结果将发布到工作簿中的另一张工作表,因为我需要查看结果中的所有 36 列。如果您需要额外的自动过滤器,那么只需添加到最后。我只使用 2 个输入框进行搜索,因为它必须快速且即时。您应该能够修改任何代码以满足您的需要。希望这会有所帮助。

Public Sub SearchForItem()
  'SEARCH FOR SOMETHING AND OPTION TO SORT BY SOMETHING ELSE
Dim lngLastRow As Long
Dim lngRow As Long
Dim strValue As String
Dim lngRowOutput As Long
Dim result As String
Dim quest1 As String


result = InputBox(prompt:="What ?", Title:="First Search Item")
   If result = vbNullString Then
       Exit Sub
   Else
' where does the data end in Sheet1
   lngLastRow = Sheet2.UsedRange.Rows.Count

   If lngLastRow = 1 Then Exit Sub ' no data

' Clear down sheet2, assume we have column headings in row 1 we want to keep
   Sheet7.Range("6:1048576").Clear

lngRowOutput = 6 ' where are we going to write the values to in Sheet7 

For lngRow = 6 To lngLastRow
    strValue = Sheet2.Cells(lngRow, 2).Value ' get value from column B

    If InStr(1, strValue, result, vbTextCompare) > 0 Then ' can we find "First Search Item" in the text
        Sheet2.Rows(lngRow).Copy
        Sheet7.Rows(lngRowOutput).PasteSpecial
        lngRowOutput = lngRowOutput + 1
    End If

Next lngRow

End If

   'Go to the results and decide whether to AutoFilter or not
    Sheets("SResults").Select
quest1 = MsgBox("Do you want to select a category ?", vbYesNo)
  If quest1 = vbNo Then
  Exit Sub
  Else
 ActiveSheet.Range("$A$5:$AG$106").AutoFilter Field:=3, Criteria1:="=*" & InputBox("Operator to search for?") & "*"
  End If
End Sub

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 2021-11-04
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多