windowsgm
windowsgm

Reputation: 1616

Using 'Contains' on an Array

Ok, so I'm not very familiar with VB6 but I'm trying to see if an array contains a value. This is what I have but it's throwing up an error to me. Could be an issue with the "passedValue" being the wrong type but I don't think so.

    Dim transCodes As Variant
    transCodes = Array(40, 41, 42, 43)
    If (transCodes.Contains("passedValue")) Then
    *Do Stuff*
    End If

Any help would be really appreciated!

UPDATE

Failing correcting my syntax, could you give me an example for the cast/convert I might use to ensure the "passedValue" was of the right type?

UPDATING MY UPDATE

So is there no 'Contains' method in VB6? Any other ways of doing this simple task?

Upvotes: 6

Views: 17983

Answers (4)

Ken Forslund
Ken Forslund

Reputation: 340

I wrapped Deanna's answer as a VB6 function:

Public Function StringArrayContains(ByRef arrString() As Boolean, PassedValue) As String
   Dim Found As Boolean
   Found = False
   Dim index  As Integer
    For Index = LBound(arrString) To UBound(arrString)
      If arrString(Index) = PassedValue Then
        Found = True
        Exit For
      End If
    Next
    StringArrayContains = Found
End Function

Upvotes: 1

AAP
AAP

Reputation: 253

Finally based on @Mostafa Anssary

I used this function

    Function instrSplit(ByVal searchEstado As String, ByVal arrayEstados As String)

       instrSplit = 0

       instrSplit = InStr(1, " " & Join(Split(arrayEstados, ","), " ") & " ", _
                " " & searchEstado & " ")

    End Function

And I Call by

found = instrSplit(mySearchValue, arrayValues)

For example

arrayValues = "8, 64, 72, 1520"
mySearchValue  = "8"


found = instrSplit(mySearchValue, arrayValues)

Upvotes: 0

Mostafa Anssary
Mostafa Anssary

Reputation: 135

If you want this in just one line, you can check whether a string array contains an item (without a loop) with the following code:

' ARR is an array of string, SEARCH is the value to be searched
Found = InStr(1, vbNullChar & Join(arr, vbNullChar) & vbNullChar, _
vbNullChar & search & vbNullChar) > 0

This was taken from a Devx tip

Upvotes: 4

Deanna
Deanna

Reputation: 24253

VB6 doesn't have a native Contains method on arrays.

Your best option is to walk the array checking each item in turn:

Found = False
For Index = LBound(transCodes) To UBound(transCodes )
  If transCodes(Index) = PassedValue Then
    Found = True
    Exit For
  End If
Next

If Found Then
  'Do stuff
  'Index will contain the location it was found
End If

Alternatives include using a collection and trying to retreive items based on their value, but this is much more work for this simple case.

Upvotes: 11

Related Questions