如何搜索字符串以阵列 [英] How to search for string in an array

查看:145
本文介绍了如何搜索字符串以阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单(单行)来搜索VBA数组中的字符串?或将我需要通过每个元素循环,并将其与目标字符串比较?

Is there an easy (one-liner) to search for a string within an array in VBA? Or will I need to loop through each element and compare it with the target string?

编辑:
它是一个一维数组。我只需要知道的如果的字符串是介于数组中的

It is a one-dimensional array. I only need to know IF a string is somewhere in the array.

IE:

names(JOHN, BOB, JAMES, PHLLIP)

我如何找出是否约翰是在数组中,它需要是最小的,因为它会围绕5000次反复,我不希望函数减缓整个过程下来。

How do I find out if "JOHN" is in the array, it needs to be minimal as it will be repeated around 5000 times and I don't want the function to slow the overall process down.

推荐答案

如果你想知道,如果该字符串数组中发现的所有,试试这个功能:

If you want to know if the string is found in the array at all, try this function:

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

由于肖恩柴指出,这必须是一个1-D阵列。

As Sean Cheshire points out, this must be a 1-D array.

示例:

Sub Test()
  Dim arr As Variant
  arr = Split("abc,def,ghi,jkl", ",")
  Debug.Print IsInArray("ghi", arr)
End Sub

(以下code的基础上,从<评论更新href=\"http://stackoverflow.com/questions/10951687/how-to-search-for-string-in-ms-access-vba-array#comment14354047_10952705\">HansUp)

如果你想在数组中的匹配元素的索引,试试这个:

If you want the index of the matching element in the array, try this:

Function IsInArray(stringToBeFound As String, arr As Variant) As Long
  Dim i As Long
  ' default return value if value not found in array
  IsInArray = -1

  For i = LBound(arr) To UBound(arr)
    If StrComp(stringToBeFound, arr(i), vbTextCompare) = 0 Then
      IsInArray = i
      Exit For
    End If
  Next i
End Function

此还假定一维数组。请记住LBOUND和UBound函数都是从零开始所以2的指数是指第三个元素,而不是第二。

This also assumes a 1-D array. Keep in mind LBound and UBound are zero-based so an index of 2 means the third element, not the second.

示例:

Sub Test()
  Dim arr As Variant
  arr = Split("abc,def,ghi,jkl", ",")
  Debug.Print (IsInArray("ghi", arr) > -1)
End Sub

如果你心里有一个具体的例子,请更新它你的问题,否则,例如code可能不适用于你的情况。

这篇关于如何搜索字符串以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆