使用 VBA 在 excel 中搜索完全匹配
Searching for exact match in excel using VBA
我有以下代码,正在创建一个搜索栏,其中包含 table 上的选项以供过滤。它工作得很好,但是我似乎无法将其精确匹配到 search/filter。例如,如果我输入 'GE' 它将 return 所有包含单词 '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
SearchString = "=*" & mySearch & "*"
您正在搜索将包含 mySearch 的任何内容。
改为SearchString = "=" & mySearch
我有以下代码,正在创建一个搜索栏,其中包含 table 上的选项以供过滤。它工作得很好,但是我似乎无法将其精确匹配到 search/filter。例如,如果我输入 'GE' 它将 return 所有包含单词 '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
SearchString = "=*" & mySearch & "*"
您正在搜索将包含 mySearch 的任何内容。
改为SearchString = "=" & mySearch