【问题标题】:Function returns always Boolean False函数总是返回 Boolean False
【发布时间】:2015-10-23 19:23:58
【问题描述】:

我有以下功能:

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,为什么?

【问题讨论】:

  • 第一遍是这样,但你继续遍历数组。如果有比赛,你需要爆发。

标签: vba excel


【解决方案1】:

您在找到needle 时忘记返回 (Exit 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
      Exit Function
    End If
  Next element
  IsInArray = False
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多