Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorten a Like statement in VBA

Tags:

vba

Is there any way to shorten this Like statement in VBA

If ibasic Like "A1*" Or ibasic Like "A2*" Or ibasic Like "A3*" Or ibasic Like "A4*" Or ibasic Like "A5*" Or ibasic Like "A6*" Or ibasic Like "A7*" Or ibasic Like "A8*" Or ibasic Like "B1*" Or ibasic Like "B2*" Or ibasic Like "B3*" Or ibasic Like "B4*" Or ibasic Like "B5*" Or ibasic Like "B6*" Or ibasic Like "B7*" Or ibasic Like "B8*" Or ibasic Like "F1*" Or ibasic Like "F2*" Or ibasic Like "F3*" Or ibasic Like "F4*" Or ibasic Like "F5*" Or ibasic Like "F6*" Or ibasic Like "F7*" Or ibasic Like "F8*" Or ibasic Like "C1*" Or ibasic Like "S1*" Then
like image 201
Rwood Avatar asked Dec 17 '22 21:12

Rwood


2 Answers

You can combine all these comparisons in just two statements by making use of brackets, which match any one character inside them:

If ibasic Like "[ABF][1-8]*" OR ibasic Like "[CS]1*" Then

The dash expresses a range of characters here.

like image 147
Erik A Avatar answered Jan 01 '23 20:01

Erik A


Pass the option in an Array(), loop through them in a separate function and return the result:

Public Sub TestMe()

    Dim myInput As String: myInput = "A243"
    Dim myLikes As Variant

    myLikes = Array("A1*", "A2*", "A3*")
    Debug.Print CheckLikes(myLikes, myInput)

End Sub

Public Function CheckLikes(myLikes As Variant, myInput As String) As Boolean
    Dim myVars As Variant

    For Each myVars In myLikes
        If myInput Like myVars Then
            CheckLikes = True
            Exit For
        End If
    Next

End Function
like image 30
Vityata Avatar answered Jan 01 '23 21:01

Vityata