如何find一个数组是否包含一个string

可能重复:
如何在MS Access VBA数组中searchstring

我目前正在一个Excelmacros,我无法find一种方法, if array.contains(mystring)

我写了下面的内容,它给了我一个消息“Invaild Qualifier”,并在If之后突出显示Mainfram

 Dim Mainfram(4) As String Mainfram(0) = "apple" Mainfram(1) = "pear" Mainfram(2) = "orange" Mainfram(3) = "fruit" For Each cel In Selection If Mainfram.Contains(cel.Text) Then Row(cel.Row).Style = "Accent1" End If Next cel 

select是一个列

任何人帮助?

嗨,太平绅士我试过你的build议,并说对象需要。 并突出如果IsInArray(cell.Text,Mainfram)然后 Heres我的完整代码

 Sub changeRowColor() Columns("B:B").Select Dim cel As Excel.Range Dim Mainfram(4) As String Mainfram(0) = "apple" Mainfram(1) = "pear" Mainfram(2) = "orange" Mainfram(3) = "Banana" For Each cel In Selection If IsInArray(cell.Value, Mainfram) Then Rows(cel.Row).Style = "Accent1" End If Next cel End Sub Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) End Function 

没关系,我发现那个愚蠢的错误…谢谢你

使用我的答案代码来一个非常类似的问题:

 Sub DoSomething() Dim Mainfram(4) As String Dim cell As Excel.Range Mainfram(0) = "apple" Mainfram(1) = "pear" Mainfram(2) = "orange" Mainfram(3) = "fruit" For Each cell In Selection If IsInArray(cell.Value, MainFram) Then Row(cell.Row).Style = "Accent1" End If Next cell End Sub Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1) End Function 

另一个简单的方法使用JOININSTR

 Sub Sample() Dim Mainfram(4) As String, strg As String Dim cel As Range Dim Delim As String Delim = "#" Mainfram(0) = "apple" Mainfram(1) = "pear" Mainfram(2) = "orange" Mainfram(3) = "fruit" strg = Join(Mainfram, Delim) strg = Delim & strg For Each cel In Selection If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _ Rows(cel.Row).Style = "Accent1" Next cel End Sub 

恐怕我不认为有这样做的捷径 – 如果只有人会写一个VB6的linq包装!

你可以编写一个函数来循环访问数组并检查每个条目 – 我认为你不会比这个更干净。

有一篇文章提供了一些细节: http : //www.vb6.us/tutorials/searching-arrays-visual-basic-6