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

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

我有以下代码,我正在努力创建一个搜索栏,其中包含表格中的选项以进行筛选。它工作得很好,但我似乎无法搜索/过滤完全匹配。例如,如果我输入'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
excel vba search exact-match
1个回答
0
投票

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

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

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