Vlookup在VBA中的for循环 [英] Vlookup in VBA within a for loop

查看:389
本文介绍了Vlookup在VBA中的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在麻烦这个宏工作。如果通过vlookup函数不等于另一个工作表上的相应值,我希望它循环遍历一个单元格并将其清除。但是我不断收到这个代码的错误:

 对于每个单元格在工作表(Sheet1)。范围(A2: A1000)
如果单元格<> Application.WorksheetFunction.VLookup(单元格,工作表(Sheet2)。范围(C3:E128),3,0)然后
cell.Interior.Color = 65535
Else
结束如果

下一个单元格



它不断返回运行时错误'1004':无法获取WorksheetFunction类的VLookup属性



任何见解非常感谢!

解决方案

您收到该错误是因为VLookup无法找到并返回任何内容。有各种方法来处理它。这里有一个例子。

  Sub Sample()
Dim cell As Range
Dim Ret

对于工作表(Sheet1)中的每个单元格范围(A2:A1000)
在错误恢复下一步
Ret = Application.WorksheetFunction.VLookup(单元格,$
工作表(Sheet2)。范围(C3:E128),3,0)
出错GoTo 0

如果Ret<> 然后
如果单元格<> Ret然后
cell.Interior.Color = 65535
如果
Ret =
结束If
下一个
End Sub


I've been having trouble getting this macro to work. I want it to loop through a range and hilight 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!!

解决方案

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

这篇关于Vlookup在VBA中的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆