我如何使用InStr来testing更广泛的价值?

我目前使用此代码来search由用户input的特定值。 但是,如果它位于string中,我想要testing它的值,例如,如果用户键入“Jon”,search结果可能是“Jon,Jonathan,Jones”等。我想我需要以某种方式利用InStrfunction,但我不知道如何设置…任何帮助,将不胜感激。

Private Sub CommandButton1_Click() ActiveSheet.Range("H1").Select Dim MyValue As String MyValue = TextBox1.Value If MyValue = "" Then MsgBox "Please enter a sales managers name!" TextBox1.SetFocus Else Application.EnableEvents = False Worksheets("Sheet2").Activate Range("A3:I200").Select Selection.ClearContents Worksheets("Sheet1").Activate Me.Hide Set i = Sheets("Sheet1") Set E = Sheets("Sheet2") Dim d Dim j d = 2 j = 2 Do Until IsEmpty(i.Range("A" & j)) If i.Range("A" & j) = MyValue Then d = d + 1 E.Rows(d).Value = i.Rows(j).Value End If j = j + 1 Loop Application.EnableEvents = True Worksheets("Sheet2").Activate ActiveSheet.Range("H1").Select If Range("A3").Value = "" Then MsgBox "No results were found." Else MsgBox "Results were found!" End If End If Unload Me End Sub 

我会使用AutoFilter() ,并做一些小的重构,如下所示:

 Private Sub CommandButton1_Click() Dim MyValue As String MyValue = Me.TextBox1.Value If MyValue = "" Then MsgBox "Please enter a sales managers name!" Me.TextBox1.SetFocus Else With Worksheets("Sheet1") With .Range("A1", .Cells(.Rows.count, 1).End(xlUp)) .AutoFilter field:=1, Criteria1:=MyValue & "*" If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Worksheets("Sheet2").UsedRange.ClearContents Intersect(.Parent.UsedRange, .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow).Copy Worksheets("Sheet2").Range("A3") MsgBox "Results were found." Else MsgBox "No results were found." End If End With .AutoFilterMode = False End With Me.Hide '<--| hide the userform and move 'Unload UserformName' command to the sub that's calling the Userform End If End Sub 

你可以很容易地用正则expression式来做这个事情,例如:

(^Jon\s)|(\sJon\s)|(\sJon$)

我会把它包装在一个函数中,允许从用户inputdynamic地构build模式。 这只是一个例子 – 你可能需要做一些更多的逃避之外. 或者(可能更好)在TextBox上添加input限制。

 'Add reference to Microsoft VBScript Regular Expressions Private Function ContainsWord(target As String, search As String) As Boolean Const template As String = "(^<word>\s)|(\s<word>\s)|(\s<word>$)" Dim expression As String expression = Replace$(template, "<word>", Replace$(search, ".", "\.")) With New RegExp .Pattern = expression ContainsWord = .Test(target) End With End Function 

示例用法:

 Public Sub Example() Debug.Print ContainsWord("foo bar baz", "bar") 'True Debug.Print ContainsWord("foo barbaz", "bar") 'False Debug.Print ContainsWord("foobar baz", "bar") 'False Debug.Print ContainsWord("bar foo baz", "bar") 'True Debug.Print ContainsWord("foo baz bar", "bar") 'True End Sub 

在你的代码中,你只需要replace行…

 If i.Range("A" & j) = MyValue Then 

…有:

 If ContainsWord(i.Range("A" & j).Value, MyValue) Then 

请注意,由于您在循环中调用它,因此您可能需要cachingRegExp ,以避免重复创build它,如果您有大量的单元格需要检查。