2

I have following function:

Function IsInArray(ByVal needle As String, haystack() As String) As Boolean
  Dim element As Variant
  For Each element In haystack
    If element = needle Then
      IsInArray = True
    End If
  Next element
  IsInArray = False
End Function

Which I'm calling via this subroutine:

Sub CallIsInArray()
  Dim haystack(1 To 4) As String
  haystack(1) = "T1"
  haystack(2) = "T2"
  haystack(3) = "T3"
  haystack(4) = "T4"

  Dim needle As String
  needle = "T1"  ' Should return True but instead of it return False
  ' needle = "T1x" ' Return False as expected

  Dim result As Boolean
  result = IsInArray(needle, haystack)
  MsgBox result
End Sub

The problem is that IsInArray always return False, why?

1
  • It's true on the first pass but you continue through the array. You need to break out if there is a match. Oct 23, 2015 at 11:14

1 Answer 1

8

You forgot to return (Exit Function) when you find the needle.

Function IsInArray(ByVal needle As String, haystack() As String) As Boolean
  Dim element As Variant
  For Each element In haystack
    If element = needle Then
      IsInArray = True
      Exit Function
    End If
  Next element
  IsInArray = False
End Function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.