string compare to array

S

SteveDB1

Hello.

Ok, I've been able to further reduce what I want to the following statement.

I have a single string.

I need to compare that string to an array of strings.

If I find my single string in that array, I want to perform task A.

Else, task B.

So, my question is:

1- how do I populate that array so I have something for comparison?

2- I thought that I could use an if statement, with Like. Is this correct?

Thank you.
 
G

Gary''s Student

How about something like:

Sub StringAlong()
sArray = Split("alpha,beta,gamma,delta,zeta,eta,theta", ",")
sample = "mm"
For i = LBound(sArray) To UBound(sArray)
If InStr(sArray(i), sample) > 0 Then
MsgBox ("found it")
Exit Sub
End If
Next
MsgBox ("did not find it")
End Sub
 
M

Mike H

Hi,

This uses a dummy Teststring to test the program

Sub Sonic()
Dim RunFlag As Boolean
teststring = "Four"
myarray = Array("One", "Two", "Three", "Four")
For x = LBound(myarray) To UBound(myarray)
If myarray(x) = teststring Then
RunFlag = True
Exit For
End If
Next
If RunFlag Then
MsgBox "Task A"
Else
MsgBox "Task B"
End If
End Sub

Mike
 
P

Per Jessen

Hi

Suppose you have strings to populate the array in A1:A10.

To compare the single string with the strings in the array, you have to loop
through the array.

See my example.

Sub aaa()
Dim MyArray(1 To 10) As String
Dim InArray As Boolean
Dim SingleString As String

SingleString = "Test"

For r = 1 To 10
MyArray(r) = Cells(r, 1).Value
Next

For r = 1 To 10
If SingleString = MyArray(r) Then
InArray = True
End If
Next

If InArray Then
msg = MsgBox(SingleString & " is found in MyArray")
End If

Regards,
Per

End Sub
 
R

Rick Rothstein

Here is another way to do it (without using a loop)...

Sub StringAlong()
sArray = Split("alpha,beta,gamma,delta,zeta,eta,theta", ",")
Sample = "mm"
If UBound(Filter(sArray, Sample)) >= 0 Then
MsgBox ("found it")
Else
MsgBox ("did not find it")
End If
End Sub
 
S

SteveDB1

IT works. Now I'll do a bit oftweaking for my need, and see how that plays out.
Thank you
 
S

SteveDB1

It works, now for a bit of tweaking to meet my need, and go from there.
Thank you Mike.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top