函数返回总是布尔值False

时间:2015-10-23 11:08:45

标签: excel vba excel-vba

我有以下功能:

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

我正在通过这个子程序调用:

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

问题是IsInArray总是返回False,为什么?

1 个答案:

答案 0 :(得分:7)

当您找到Exit Function时,您忘了返回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