Thread: string matching
View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein \(MVP - VB\) Rick Rothstein \(MVP - VB\) is offline
external usenet poster
 
Posts: 2,202
Default string matching

I have newbie question on how to match strings with excel macro.
What I want is to match a word against different elements of an array
and do something with it if matches.

Lets say I have an array like the one below and now I want to output
(msgbox) every time the string "apple" appears. How would I do this?
In perl it would be trivial with something like =~ /.apple./

----------------------------------------------
Dim arr() As Variant
ReDim arr(3)
arr(1) = "apple tree"
arr(2) = "I like apples"
arr(3) = "pears are good for you"

For x = 1 To 3
If arr(x) = "*apple*" Then
msgbox arr(x)
end if

Next
----------------------------------------------


You could use the InStr method Norman posted, or one that looks almost like
a regular expression...

For x = 1 To 3
If arr(x) Like "*[aA]pple*" Then
MsgBox arr(x)
End If
Next x

where the [aA] allows "apple" to start with either a lower or upper case
"A".

Another possibility is to use the Filter function to create an array of just
elements from the original array that contain the search word (apple, in
your case) and also note the alternate way of assigning values to your
array...

Public Sub Tester()
Dim X As Long
Dim Arr() As String
Dim SubArr
Arr = Split("apple tree|I like apples|pears are good for you", "|")
SubArr = Filter(Arr, "apple", , vbTextCompare)
For X = 0 To UBound(SubArr)
MsgBox Arr(X)
Next X
End Sub


Rick