在 VBA 中使用 Vlookup 和过滤条件

Using Vlookup In VBA With Filter Conditions

我想在这里完成的是

1) Is to iterate the values in column O and for the ones that are not null - filter the worksheet titled DATA to only show values where Column B = X and use VLOOKUP() to return the lookup values to the corresponding row in Column P
2) If column O is null then filter the sheet titled DATA to only show values where Column B <> X and use VLOOKUP() to return the lookup values to the corresponding row in Column P.

我尝试了下面的语法,但出现了

的错误

Method 'Rarnge' of object '_Worksheet' failed

我需要在下面的代码中做哪些不同的事情才能获得 return 我想要的值的语法?

Dim destSheet As Worksheet: Set destSheet = Sheets("Main")

For i = Range("A" & Rows.Count).End(3).Row To 2 Step -1
    If Not IsEmpty(Cells(i, "O").Value) Then
        Sheets("Data").Select
        Selection.AutoFilter
        ActiveSheet.Range("$A:$C").AutoFilter Field:=2, Criteria1:="<>"
        Sheets("Main").Select
        Application.CutCopyMode = False
        form2 = "=IFERROR(VLOOKUP(RC[-15],Lookup!C[-15]:C[-13],3,FALSE),"""")"
        destSheet.Range("P:P" & lr).Formula = form2
    Else
        Sheets("Data").Select
        Selection.AutoFilter
        Sheets("Main").Select
        Application.CutCopyMode = False
        form3 = "=IFERROR(VLOOKUP(RC[-15],Lookup!C[-15]:C[-13],3,FALSE),"""")"
        destSheet.Range("P:P" & lr).Formula = form3
    End If
Next i

我有点难以理解你想做什么,如果我理解错了请纠正我。

首先,选择工作表不是首选方法,而 运行 宏,除非你有意这样做,否则请避免。

其次,您不需要过滤任何东西,您可以通过检查代码中的条件来控制它。你不做物理上的事情,你在你的代码中理论上做它们,并显示输出。 看看这段代码,并在需要帮助的地方询问。

Sub VLookups()

Dim destSheet As Worksheet: Set destSheet = Sheets("Main")
Dim i As Long
Dim myVal As Variant

Set lookupRange = Sheets("Data").Range("$A:$C") 'This is your lookup range

For i = 2 To Range("O" & Rows.Count).End(xlUp).Row 'Iterate from 2nd row till last row
    myVal = Application.VLookup(destSheet.Cells(i, "A").Value, lookupRange, 2, False)
    If IsError(myVal) Then GoTo Skip 'If searched value not found then skip to next row

    If Not IsEmpty(Cells(i, "O").Value) Then 'If Cell in Column O not empty
        If myVal = "YOUR X VALUE FOR COLUMN B" Then 'If Your Column B X value exists
            destSheet.Cells(i, "P").Value = Application.VLookup(destSheet.Cells(i, "A").Value, _
            lookupRange, 3, False) 'Column P Cell is populated by Data Sheet Column C Cell
        End If
    Else 'If Cell in Column O empty
        If myVal <> "YOUR X VALUE FOR COLUMN B" Then 'If Your Column B X value not exists
            destSheet.Cells(i, "P").Value = Application.VLookup(destSheet.Cells(i, "A").Value, _
            lookupRange, 3, False) 'Column P Cell is populated by Data Sheet Column C Cell
        End If
    End If
Skip:
Next i
End Sub