【问题标题】:Which function for finding if a string is in an array (VBA) is better?查找字符串是否在数组(VBA)中的哪个函数更好?
【发布时间】:2015-06-12 23:12:23
【问题描述】:

我有 2 个函数可以检查数组中是否存在字符串。 我不知道哪个更好,以及是否有任何理由使用其中一个。任何帮助,将不胜感激。谢谢你:)

功能1

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

功能2

Function IsInArray(myArray As Variant, val As String) As Boolean
    Dim i As Integer, found As Boolean
    found = False

    If Not Len(Join(myArray)) > 0 Then
        found = False
    Else
        For i = 0 To UBound(myArray)
            If myArray(i) = val Then
               found = True
            End If
        Next i
    End If
    IsInArray = found
End Function

【问题讨论】:

  • 设置found = True 后,您不必在第二个函数中继续循环。就做IsInArray = True : Exit Function
  • 这两个函数做不同的事情。使用 Filter 也将匹配子字符串,而您的第二个函数仅在存在 exact 匹配时才返回 true。
  • 谢谢你们俩。这些 cmets 帮助

标签: arrays string vba function


【解决方案1】:

这就是我会做的。

For each thing in Arr
    If instr(Thing, StringToBeFound) > 0 then msgbox thing
Next

您的第二个函数使用大量内存和一个大数组。

这就是连接字符串时发生的情况。我不知道 Join 函数是否使用字符串构建。我怀疑它没有其他基本功能。所以普通的连接会在内存周围洗牌很多字节。

字符串连接

并且不要一次连接一个字符。从 VBScript 程序员那里看到这个。它需要 50,000 字节和多次分配和释放才能生成 100 个字符的字符串。

http://blogs.msdn.com/b/ericlippert/archive/2003/10/20/53248.aspx

PS:我们在 VBA 中有 Mid 语句(不要与 Mid 函数混淆),它允许将字符串构建作为混洗字节的通用解决方案。它只对大型数组/字符串很重要。

【讨论】:

  • 您对此进行了基准测试吗? OP 的功能 1 应该很容易胜过这个。
【解决方案2】:

这两种解决方案都应该有效。第一个小而直接,而且它返回匹配的次数。

第二种解决方案的优点是“在您的控制之下”,因为您知道自己在做什么。例如,稍作修改即可返回第一个匹配项的位置。您可以通过在“found = true”之后添加语句“Exit For”来使其更快,因为无需进一步检查......

【讨论】:

    【解决方案3】:

    感谢在这个线程中输入的几个人,我能够创建这个解决方案

    Function IsInArrayyyy(stringToBeFound As String, arr As Variant) As Boolean
        For Each thing In arr
            If InStr(thing, stringToBeFound) > 0 Then
                If Len(thing) = Len(stringToBeFound) Then 'remove this if exact match not needed
                    IsInArrayyyy = True: Exit Function
                End If  'remove this if exact match not needed
            End If
        Next
    End Function
    

    【讨论】:

      猜你喜欢
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2018-05-13
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多