Vlookup in VBA within a for loop [duplicate]

↘锁芯ラ 提交于 2019-12-10 17:53:10

问题


I've been having trouble getting this macro to work. I want it to loop through a range and highlight a cell if it does not equal the corresponding value on another sheet through the vlookup function. But I keep getting an error with this code:

For Each cell In Worksheets("Sheet1").Range("A2:A1000")
    If cell <> Application.WorksheetFunction.VLookup(cell, Worksheets("Sheet2").Range("C3:E128"), 3, 0) Then
        cell.Interior.Color = 65535
    Else
    End If
Next cell

it keeps returning

Run-time error '1004': Unable to get the VLookup property of the WorksheetFunction class

any insight is much appreciated!!


回答1:


You are getting that error because the VLookup is not able to find and return anything. There are various ways to handle it. Here is one example.

Sub Sample()
    Dim cell As Range
    Dim Ret

    For Each cell In Worksheets("Sheet1").Range("A2:A1000")
        On Error Resume Next
        Ret = Application.WorksheetFunction.VLookup(cell, _
              Worksheets("Sheet2").Range("C3:E128"), 3, 0)
        On Error GoTo 0

        If Ret <> "" Then
            If cell <> Ret Then
                cell.Interior.Color = 65535
            End If
            Ret = ""
        End If
    Next
End Sub



回答2:


Try this code

WorksheetFunction.Vlookup v/s Application.Vlookup

On Error Resume Next

For Each cell In Worksheets("Sheet1").Range("A2:A1000")
    Result = Application.VLookup(cell, Worksheets("Sheet2").Range("C3:E128"), 3, 0)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        cell.Interior.Color = 65535
    End If

Next

On Error GoTo 0



回答3:


Usually "Unable to get the .... property of the WorksheetFunction" arises because there is something wrong with the arguments passed to the function.

For example, if any cell within your range contains an error, it will occur



来源:https://stackoverflow.com/questions/19057369/vlookup-in-vba-within-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!