在另一个内搜索一个列表

时间:2016-05-20 10:48:37

标签: excel vba

我编写了一个近乎工作的脚本,用于在A列的较大列表中搜索B列中的单词列表。

Sub QualifierArray()

Sub QualifierArray()
    Dim List As Worksheet
    Set List = Sheets("List")
    Dim lastRow As Long
    lastRow = (List.Cells(Rows.Count, 1).End(xlUp).Row) 'removed +1
    Dim listColumn As Variant
    listColumn = List.Range("A1:A" & lastRow)
    Dim outputArray As Variant
    Dim intQualifier As Long
    Dim lastQualifier As Range
    ReDim outputArray(1 To lastRow)
    Dim i As Long
    Dim j As Long
    Dim index As Long
    index = 1
    intQualifier = Range("B" & Rows.Count).End(xlUp).Row
        For j = 1 To intQualifier
            For i = 1 To lastRow
                Set rngQualifier = Range("B" & j)
                If InStr(listColumn(i, 1), rngQualifier) > 0 Or InStr(listColumn(i, 1), "[") > 0 Then 'changed = to >
                    outputArray(index) = listColumn(i, 1)
                    index = index + 1
                End If
            Next
        Next
End Sub

然而,我得到的"下标超出范围"对于outputArray。似乎索引已经增加到超过lastRow,这导致了错误。我尝试了各种修复,比如添加is not empty这样的额外条款,但无济于事。有没有人对导致错误的原因有任何建议?一个线索是删除Or InStr(listColumn(i, 1), "[") = 0部分'可以完美地使代码(当然没有这个子句)。我接近解决方案了吗?感觉好像离这儿不远......

提前致谢!

1 个答案:

答案 0 :(得分:0)

尝试以下代码

Sub QualifierArray()
    Dim List As Worksheet
    Set List = Sheets("List")
    Dim lastRow As Long
    lastRow = (List.Cells(Rows.Count, 1).End(xlUp).Row) 'removed +1
    Dim listColumn As Variant
    listColumn = List.Range("A1:A" & lastRow)
    Dim outputArray As Variant
    Dim intQualifier As Long
    Dim lastQualifier As Range
    ReDim outputArray(1 To lastRow)
    Dim i As Long
    Dim j As Long
    Dim index As Long
    index = 1
    intQualifier = Range("B" & Rows.Count).End(xlUp).Row
        For j = 1 To intQualifier
            For i = 1 To lastRow
                Set rngQualifier = Range("B" & j)
                If InStr(listColumn(i, 1), rngQualifier) > 0 Or InStr(listColumn(i, 1), "[") > 0 Then 'changed = to >
                    outputArray(index) = listColumn(i, 1)
                    index = index + 1
                End If
            Next
        Next
End Sub

注意:在评论中标记的更改