使用VBA在Excel中搜索完全匹配

时间:2019-03-13 08:40:54

标签: excel vba search exact-match

我有以下代码,并且正在创建一个搜索栏,其中带有要过滤的表格上的选项。它运行完美,但是我似乎无法让它搜索/过滤精确匹配。例如,如果我输入“ GE”,它将返回单词中包含“ GE”的所有匹配项,而我只希望两个字母一起位于的那些字段。

有人可以帮助我调整代码吗?

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

'Retrieve User's Search Input

  mySearch = sht.OLEObjects("Hello").Object.Text 'ActiveX Control


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

'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

1 个答案:

答案 0 :(得分:0)

SearchString = "=*" & mySearch & "*"您正在搜索任何包含mySearch的内容。

将其更改为SearchString = "=" & mySearch