Excel VBA wildcard search

*爱你&永不变心* 提交于 2019-11-28 02:05:16

You can use Like operator (case-sensitive):

Private Sub search_Click()
    For firstloop = 3 To 10
        If Range("G" & firstloop).Text Like name.Text & "*" Then
            MsgBox "Found!"
            Exit Sub
        Else
            MsgBox "NOT FOUND"
        End If
    Next
End Sub

for case-insensitive search use:

If UCase(Range("G" & firstloop).Text) Like UCase(name.Text) & "*" Then

Also if you want to determine whether cell contains text (not only starts with text), you can use (case-sensitive):

If InStr(1, Range("G" & firstloop).Text, name.Text) > 0 Then

or (case-insensitive)

If InStr(1, Range("G" & firstloop).Text, name.Text, vbTextCompare) > 0 Then

UPD:

If the point only to show msgbox, then I'd suggest to use Application.Match:

Private Sub search_Click()
    If Not IsError(Application.Match("abc" & "*", Range("G3:G10"), 0)) Then
        MsgBox "Found!"
    Else
        MsgBox "NOT FOUND"
    End If
End Sub

You can also avoid a loop and use the Range.Find Method. You can pass as option if you want it case sensitive or not. (By default it is not case sensitive.)

Set rngFound= Range("G" & firstloop).Find(name.Text & "*") 
If rngFound Is Nothing Then
    MsgBox "Not Found!"
Else           
    MsgBox "FOUND"
End If
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!