Dynamic Searching for exact and partial matches in excel using option buttons

邮差的信 提交于 2019-12-25 01:03:27

问题


I have the following code that allows me to search through the data on a table by using the option buttons I created that match the table headings. I can set the search criteria to be exact matches or partial. However, what I would like is to be able to search through different columns in the table without always having to go into the VBA code to toggle this option on and off. i.e some columns I would like an exact match, others I would like partial.

Any help on where I can amend the code below?

Sub SearchBox()

Dim myButton As OptionButton
Dim SearchString As String
Dim ButtonName As String
Dim sht As Worksheet
Dim myField As Long
Dim DataRange As Range
Dim mySearch As Variant

'Load Sheet into A Variable
  Set sht = ActiveSheet

'Unfilter Data (if necessary)
  On Error Resume Next
    sht.ShowAllData
  On Error GoTo 0

'Filtered Data Range (include column heading cells)
  'Set DataRange = sht.Range("E5:H200") 'Cell Range
   Set DataRange = sht.ListObjects("Table1").Range 'Table

'Retrieve User's Search Input
  'mySearch = sht.Shapes("UserSearch").TextFrame.Characters.Text 'Control Form
  mySearch = sht.OLEObjects("Hello").Object.Text 'ActiveX Control
  'mySearch = sht.Range("A1").Value 'Cell Input

'Determine if user is searching for number or text
  If IsNumeric(mySearch) = True Then
    SearchString = "=" & mySearch
  Else

  'change this to =* if you want to search for anything that containts mysearch rather than just mysearch
    SearchString = "=*" & mySearch & "*"

    End If

'Loop Through Option Buttons
  For Each myButton In sht.OptionButtons
    If myButton.Value = 1 Then
      ButtonName = myButton.Text
      Exit For
    End If
  Next myButton

'Determine Filter Field
  On Error GoTo HeadingNotFound
    myField = Application.WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)
  On Error GoTo 0

'Filter Data
  DataRange.AutoFilter _
    Field:=myField, _
    Criteria1:=SearchString, _
    Operator:=xlAnd

'Clear Search Field
  'sht.Shapes("UserSearch").TextFrame.Characters.Text = "" 'Control Form
  sht.OLEObjects("Hello").Object.Text = "" 'ActiveX Control
  'sht.Range("A1").Value = "" 'Cell Input

Exit Sub

'ERROR HANDLERS
HeadingNotFound:
  MsgBox "The column heading [" & ButtonName & "] was not found in cells " & DataRange.Rows(1).Address & ". " & _
    vbNewLine & "Please check for possible typos.", vbCritical, "Header Name Not Found!"

End Sub


Sub ClearFilter()
'PURPOSE: Clear all filter rules

'Clear filters on ActiveSheet
  On Error Resume Next
  ActiveSheet.ListObjects(1).AutoFilter.ShowAllData

  On Error GoTo 0

End Sub

回答1:


Modify and try the below:

Option Explicit

Sub test()

    Dim ws As Worksheet
    Dim SearchValue As String, FullReport As String
    Dim rng As Range, cell As Range

    'What i m looking for
    SearchValue = "Test"

    'Where to look for
    Set rng = ThisWorkbook.Worksheets("Sheet1").UsedRange

    For Each cell In rng

        If cell.Value = SearchValue Then
            If FullReport = "" Then
                FullReport = "The word " & SearchValue & " appears in " & "Column " & cell.Column & ", Row " & cell.Row & "."
            Else
                FullReport = FullReport & vbNewLine & "The word " & SearchValue & " appears in " & "Column " & cell.Column & ", Row " & cell.Row & "."
            End If
        End If

    Next cell

    MsgBox FullReport

End Sub



回答2:


If you have a fixed list of columns, then simply move the code where you set the SearchString below the part where you determine which column you want to search and check the selected field against this list. However, I would suggest to put this is a separate function:

Function getSearchString(searchVal as variant, searchFieldName as string)
    If IsNumeric(searchVal) Then
        getSearchString = "=" & searchVal 
    ElseIf searchFieldName = "MyField1" _
        Or searchFieldName = "MyField2" _
        Or (... List all fields where you want to search partial) Then
        getSearchString = "=*" & searchVal & "*"
    Else
        getSearchString = "=" & searchVal
    End If
End Function

You call the function after setting the var ButtonName.

    searchStr = getSearchString(mySearch, ButtonName)

(you can of course think about a more sophisticated way to determine if or if not to use partial searching - or maybe add a CheckBox to let the user choose)



来源:https://stackoverflow.com/questions/55257762/dynamic-searching-for-exact-and-partial-matches-in-excel-using-option-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!