在VBA vlookup中返回第二个值

时间:2016-08-10 10:16:23

标签: vba vlookup

我确信这很容易,但无法找到办法。我试图计算A列中的范围,如果< 2然后可以只是常规vlookup返回一个答案但是如果大于2我希望vlookup在第9列中返回第一个答案然后在第10列中返回第二个等可以任何人救命?希望这是有道理的谢谢。

    If (Application.WorksheetFunction.CountIf _       
 (data.Range("A:A"), ThisWorkbook.Sheets("Sheet2").Cells(r, 2).Value)) < 2 _
        Then
        toh = Application.WorksheetFunction.VLookup _
        (ThisWorkbook.Sheets("Sheet2").Cells(r, 2).Value, data.Range("A:N"), 14, False)
        Cells(r, 9) = toh

3 个答案:

答案 0 :(得分:0)

下面的功能可以让您了解vloopkup的工作原理 函数f_Apply_VlookupCalculation_Formulas(arrLookupWs,arrlookupRange,lookupColNo)         &#39; arrlookupRange =&#34; $ A $ 2:$ E $ 2413&#34;         &#39; arrLookupWs =数组(&#34; DD&#34;,&#34; MM&#34;)         &#39; lookupColNo = 5         intRowCount = Int(ActiveSheet.UsedRange.Count)         On Error Resume Next         对于x = 2到intRowCount             ActiveSheet.Cells(x,4).Value = Application.WorksheetFunction.VLookup(ActiveSheet.Cells(x,1).Value,Sheets(arrLookupWs(0))。Range(arrlookupRange(0)),lookupColNo - 1,0)             ActiveSheet.Cells(x,5).Value = Application.WorksheetFunction.VLookup(ActiveSheet.Cells(x,1).Value,Sheets(arrLookupWs(0))。Range(arrlookupRange(0)),lookupColNo,0)             ActiveSheet.Cells(x,6).Value = Application.WorksheetFunction.VLookup(ActiveSheet.Cells(x,1).Value,Sheets(arrLookupWs(1))。Range(arrlookupRange(1)),lookupColNo - 1,0)             ActiveSheet.Cells(x,7).Value = Application.WorksheetFunction.VLookup(ActiveSheet.Cells(x,1).Value,Sheets(arrLookupWs(1))。Range(arrlookupRange(1)),lookupColNo,0)         下一个         On Error GoTo 0         擦除arrLookupWs         擦除arrlookupRange         结束功能

答案 1 :(得分:0)

可以使用数组公式

来完成

这将给出第1个,正常的vlookup

=INDEX(I$1:I$13,SMALL(IF($A$1:$A$13=$A$15,ROW($A$1:$A$13)),1),1)

这将给出第二个

=INDEX(J$1:J$13,SMALL(IF($A$1:$A$13=$A$15,ROW($A$1:$A$13)),**2**),1)

这是第3次,每次加星号,删除星星

=INDEX(K$1:K$13,SMALL(IF($A$1:$A$13=$A$15,ROW($A$1:$A$13)),**3**),1)

不确定您是否将VBA用于工作表功能或更大功能。

或类似的东西,其中查找的是你正在做的数据的单元格,检查值是列a,输入范围是你想要的返回,你的列8到.....和列是返回,所以要获得第二个值,与公式ID相同的数据使用

VLOOKUP_NEW (range("a15"),range("a1:a13"),range("i1:k13"),2)

Public Function VLOOKUP_NEW(rngLookFor As Excel.Range, _
                        rngCheckValues As Excel.Range, _
                        rngInputRange As Excel.Range, _
                        colReturn As Integer) As Variant

Dim c As Excel.Range
Dim arrRows() As Long

On Error GoTo eHandle

For Each c In rngCheckValues.Cells
    If c.Value = rngLookFor.Value Then
        arrRows(UBound(arrRows)) = c.Row
        ReDim Preserve a(UBound(arrRows) + 1)
    End If
Next c

VLOOKUP_NEW = WorksheetFunction.Index(rngInputRange, arrRows(colReturn - 1), colReturn)

Exit Function

eHandle:
    If Err.Number = 9 Then
        ReDim arrRows(0)
        Resume
    End If
End Function

答案 2 :(得分:0)

你试试这个:

volatile