Compare a string against a set of strings

megahurtz

New Member
Joined
Aug 16, 2011
Messages
17
Hi All,

I have to compare a string against a set of substrings.

However, the number of substrings to be matched with is not fixed. Thereby I'm confused how to write my IF statement.

For eg. if the string in tbl_nm is to be compared against these substrings FACT*, STG*, DIM*, the code would look like:

Code:
sub test()

tbl_nm = "FACT_CONTROL_ABC"

If tbl_nm Like "FACT*" or tbl_nm Like "STG*" or tbl_nm Like "DIM*" then
' Do Something
End If

end sub
There may be even different substrings to be compared with. So the IF statement can't be hard-coded. How do I write the IF logic effectively?????

Please Help. Thanks a lot in advance... :)
 

Excel Facts

Excel Wisdom
Using a mouse in Excel is the work equivalent of wearing a lanyard when you first get to college
Code:
Dim flag As Boolean
Dim onePattern as Variant

tbl_nm = "FACT_CONTROL_ABC"

flag = False
For Each onePattern in Array("FACT*", "STG*", "DIM*")
    flag = flag Or (tbl_nm Like onePattern)
Next onePattern

If flag Then
    Rem do something
End If
 
Upvote 0
A suggested small amendment below. You can exit the test once you have a True result rather as further testing is redundant - this may make a significant time difference depending on how many comparisons you are running

hth

Dave

Code:
   Dim bFlag As Boolean
    Dim onePattern As Variant
    tbl_nm = "FACT_CONTROL_ABC"
    bFlag = False
    For Each onePattern In Array("FACT*", "STG*", "DIM*")
        If tbl_nm Like onePattern Then
            bFlag = True
            Exit For
        End If
    Next onePattern

    If bFlag Then
        Rem do something
    End If
 
Upvote 0

Forum statistics

Threads
1,224,574
Messages
6,179,629
Members
452,933
Latest member
patv

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top