59

可能重复:
如何在 MS Access VBA 数组中搜索字符串

我目前正在处理 Excel 宏,但找不到类似的方法 if array.contains(mystring)

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

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

选择是一列

有人帮忙吗?

嗨,JP 我试过你的建议,它说需要对象。并突出显示 If IsInArray(cell.Text, Mainfram) Then 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

没关系,我发现了那个愚蠢的错误......无论如何,谢谢你

4

4 回答 4

140

使用我对一个非常相似的问题的回答中的代码:

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
于 2012-06-20T03:08:22.383 回答
17

JOIN另一种使用和的简单方法INSTR

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
于 2012-06-20T03:57:31.913 回答
5

使用此处所示的 Filter() 方法 - https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filter-function

于 2012-06-19T21:46:42.797 回答
1

恐怕我认为没有捷径可以做到这一点 - 如果有人会为 VB6 编写一个 linq 包装器!

您可以编写一个函数,通过遍历数组并检查每个条目来完成它 - 我认为您不会比这更干净。

有一篇示例文章在这里提供了一些详细信息:http ://www.vb6.us/tutorials/searching-arrays-visual-basic-6

于 2012-06-19T21:45:57.497 回答