Vlookup在一个列的两个不同区域

问题描述 投票:0回答:2

我有一个工作表(工作表1),其中包含一个包含数字“5”或文本“无效”的帮助列AR。如果AR包含数字“5”,我希望列AS执行特定的vlookup,但如果它包含文本“invalid”则执行单独的特定vlookup。目前我刚刚覆盖了我的循环的else部分所做的事情,是对列的最后一次迭代,最后只为其中一个进行了vlookup。我在工作表1中使用列Y作为用于vlookup的特定值(aCell)。任何帮助都会有很长的路要走,谢谢!

Dim wsThis As Worksheet
Dim aCell As Range
Set wsThis = Sheets("Sheet3")
Dim wsAnd As Worksheet
Set wsAnd = Sheets("Sheet2")
Dim LastRow As Long, myRng As Range
LastRow = Sheets("Sheet3").UsedRange.Rows.Count
With wsIt
    For x = 2 To LastRow
        If Sheets("Sheet1").Range("$AR$" & x) = "5" Then
            For Each aCell In wsIt.Range("Y2:Y" & LastRow)
                .Cells(aCell.Row, 45) = "Not Found"
                On Error Resume Next
                .Cells(aCell.Row, 45) = Application.WorksheetFunction.VLookup( _
                                aCell.Value, wsThis.Range("$B$2:$Q$400"), 5, False)
                On Error GoTo 0
            Next aCell
        End If
    Next
End With

With wsIt
    For x = 2 To LastRow
        If Sheets("Sheet1").Range("$AR$" & x) = "Invalid" Then
            For Each aCell In wsIt.Range("Y2:Y" & LastRow)
                .Cells(aCell.Row, 45) = "Not Found"
                On Error Resume Next
                .Cells(aCell.Row, 45) = Application.WorksheetFunction.VLookup( _
                                aCell.Value, wsAnd.Range("$B$2:$Q$400"), 5, False)
                On Error GoTo 0
            Next aCell
        End If
    Next
End With
excel vba for-loop if-statement vlookup
2个回答
1
投票

如果我正确地指望你的目标,你可以:

  • 使用Application.VlookUp()方法从其返回值中获益,捕获任何错误并查询它
  • 使用Select Case块以前选择与“AR”列相关的lookUp范围 Dim wsIt As Worksheet Set wsIt = Sheets("Sheet1") Dim wsThis As Worksheet Set wsThis = Sheets("Sheet3") Dim wsAnd As Worksheet Set wsAnd = Sheets("Sheet2") Dim LastRow As Long Dim aCell As Range Dim lookUpResult As Variant LastRow = wsThis.UsedRange.Rows.Count With wsIt For x = 2 To LastRow Select Case .Cells(x, "AR") Case "5" Set VLookUpRng = wsThis.Range("$B$2:$Q$400") Case “Invalid” Set VLookUpRng = wsAnd.Range("$B$2:$Q$400") Case Else Set VLookUpRng = Nothing End Select If Not VLookUpRng Is Nothing Then For Each aCell In .Range("Y2:Y" & LastRow) lookUpResult = Application.VLookup( aCell.Value, VLookUpRng, 5, False) .Cells(aCell.Row, 45) = IIf(IsError(lookUpResult), "Not Found", lookUpResult) Next End If Next End With

0
投票

这不是一个很好的解决方案,但基本上我将第二次迭代的vlookup结果粘贴到一个新工作表中,然后对工作表1和工作表2的列进行排序,以便结果可以正确地相互引用。

Dim x as Long
Dim y As Long
Dim LastRow
Dim NewLast
    LastRow = Sheets("Sheet1").UsedRange.Rows.Count
    NewLast = Sheets("Sheet2").UsedRange.Rows.Count
For x = 2 to LastRow 
    If Sheets("Sheet1").Range("$AS$" & x) = "Not Found" Then
        For y = 2 To NewLast
            Sheets("Sheet1").Range("$AS$" & x) = Sheets("Sheet2").Range("$F$" & y)
            Sheets("Sheet1").Range("$AT$" & x) = Sheets("Sheet2").Range("$F$" & y)
        Next
    End If
Next
© www.soinside.com 2019 - 2024. All rights reserved.