Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'Contains' on an Array

Tags:

arrays

vb6

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?

like image 449
windowsgm Avatar asked May 23 '12 13:05

windowsgm


2 Answers

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.

like image 126
Deanna Avatar answered Oct 21 '22 14:10

Deanna


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

like image 44
Mostafa Anssary Avatar answered Oct 21 '22 16:10

Mostafa Anssary