使用Excel的VBA对已过滤的数据进行Vlookup处理

时间:2018-12-13 13:28:07

标签: excel vba vlookup

Sub FilteredTest()

    Dim LastRow1 As Long
    Dim LastRow2 As Long
    Dim myI As Long
    Dim myLookupvalue As Long
    Dim myTableArray As Range

    LastRow1 = Worksheets(2).Cells(Cells.Rows.Count, "A").End(xlUp).Row
    LastRow2 = Worksheets(8).Cells(Cells.Rows.Count, "A").End(xlUp).Row

    Set myTableArray = Worksheets(2).Range("A2:A" & LastRow1)

    myI = 3

    Do Until myI > LastRow2

        myLookupvalue = Worksheets(8).Range("E" & myI)
        On Error Resume Next
        Worksheets(8).Range("H" & myI).Value = WorksheetFunction.VLookup(myLookupvalue, myTableArray, 1, False)
        ' Error 1004 is when the VLOOKUP can't find a corresponding value
        If Err = 1004 Then
            Worksheets(8).Range("H" & myI).Value = "Remove"
        End If
        myI = myI + 1

    Loop
End Sub

我需要一些帮助,以使此代码仅针对另一个工作表中的可见值进行Vlookup处理。

基本上我想做的是,在主表中的另一张数据表中的 A 列中有 H#列,并给出常规的Iferror w /主表中 E#列中的Vlookup输出。

我在循环内和循环内都尝试了 SpecialCells(xlCellTypeVisible)-函数的多个放置,但是我似乎无济于事。我得到的只是代码中的错误或Vlookup上的错误。 我尝试在此网站上搜索并像疯子一样谷歌搜索。在这一点上扔毛巾,并决定自己开始线程。希望有人可以帮助我将该功能集成到我的代码中和/或帮助我更好地理解此功能。

1 个答案:

答案 0 :(得分:0)

您可以添加此用户定义函数,然后换出WorksheetFunction.VLookup来使用此新的“帮助”函数。

Option Explicit

Function VisLookup(lu As Variant, rng As Range, col As Long, _
                   Optional bin As Boolean = False) As Variant

    Dim i As Long

    Set rng = Intersect(rng, rng.Parent.UsedRange)
    VisLookup = CVErr(xlErrNA)
    If col > rng.Columns.Count Then Exit Function

    If bin Then

        For i = 1 To rng.Rows.Count
            If rng.Cells(i + 1, "A").Value2 > lu And Not rng.Rows(i).Hidden Then
                VisLookup = rng.Cells(i, col).Value
                Exit For
            End If
        Next i

    Else

        For i = 1 To rng.Rows.Count
            If lu = rng.Cells(i, "A").Value2 And Not rng.Rows(i).Hidden Then
                VisLookup = rng.Cells(i, col).Value
                Exit For
            End If
        Next i

    End If

End Function

实现为

Worksheets(8).Range("H" & myI).Value = VisLookup(myLookupvalue, myTableArray, 1, False)
相关问题