VBA代码在集合的for循环中使用Vlookup

时间:2017-07-23 23:28:16

标签: excel vba

我很难将Vlookup集成到for循环中我必须显示我的集合的每个值。如果我必须检查列中的单元格以确保它们是合格的助记符,则在此背景。我有可能的所有助记符列表,所以如果vlookup返回一个值,那么它是一个助记符。为了快速检查,我的集合将显示不同的值,我试图在不同的值旁边显示vlookup结果。我无法让vlookup循环播放,我想我还需要一个错误处理程序,我只是无法准确地确定如何执行它。它现在编码的方式适用于第一个值,但它不会循环,如果第一个值不是助记符,它就不会工作。

Sub QualityAssurance()

    Dim lngLastRow As Long
    Dim rngCell As Range, _
        rngMyData As Range
    Dim clnMyList As New Collection
    Dim varMyList As Variant
    Dim strMyList As String
    Dim Mtch As Variant

    'Assumes the dataset is from A2 to A[whatever the last row in Column A is].
    'Change to suit
    lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
    Set rngMyData = Range("A2:A1000" & lngLastRow)

    Application.ScreenUpdating = False

    On Error Resume Next 'Need to ignore errors as a Collection can only contain unique values
        For Each rngCell In rngMyData
            clnMyList.Add Item:=rngCell.Value, Key:=CStr(rngCell.Value)
        Next rngCell
    On Error GoTo 0 'Nullify error handler

    For Each varMyList In clnMyList



        If strMyList = "" Then

            strMyList = varMyList & " = " & Application.WorksheetFunction.VLookup(varMyList, Sheet1.Range("P2:Q8"), 2, 0)


            Else:


            strMyList = strMyList & vbNewLine & varMyList

        End If
    Next varMyList

    MsgBox strMyList

    Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:2)

如果删除WorksheetFunction,则在没有匹配的情况下不会出现运行时错误,您可以改为测试返回值以查看是否有错误:

Dim r

'....
For Each varMyList In clnMyList

    If Len(strMyList) > 0 Then strMyList = strMyList & vbNewLine

    r = Application.VLookup(varMyList, Sheet1.Range("P2:Q8"), 2, 0)

    strMyList = strMyList & varMyList & " = " & _
                IIf(IsError(r), "?Not Found?", r)

Next varMyList