VBA第二场比赛有两个列标准

时间:2017-10-25 21:23:15

标签: vba match multiple-columns

我正在尝试开发一个代码,该代码带来了用户选择的第n个匹配,我已经找到了执行此代码但只有一列的代码

我想第三次出现字符串" castro"但是行值a2是" 19"。有什么建议吗?

下面是我用来获得第二次出现但仅使用一列的代码。

      Sub test1()
      Dim teste As String
      teste = VLOOKUPNTH("prysmian", Range("B1:C22"), 2, 2)
      End Sub

      Function VLOOKUPNTH(lookup_value, table_array As Range, col_index_num 
      As Integer, nth_value)

      Dim nRow As Long
      Dim nVal As Integer
      Dim bFound As Boolean

      VLOOKUPNTH = "No Match"

      With table_array
      For nRow = 1 To .Rows.Count
      If .Cells(nRow, 1).Value = lookup_value Then
        nVal = nVal + 1
      End If
        If nVal = nth_value Then
            VLOOKUPNTH = .Cells(nRow, col_index_num).Text
            Exit Function
        End If
      Next nRow
      End With
      End Function


     the table 
     A       B      C
     a1    castro   1
     a1    castro   3
     a1    castro   4
     a1    castro   5
     a1    castro   6
     a1    castro   7
     a2    castro   17
     a2    castro   18
     a2    castro   19
     a2    castro   20
     a2    castro   21
     a2    castro   22
     a2    castro   23

1 个答案:

答案 0 :(得分:0)

我修改了你的代码,以便检查两列。

1. Changed the range to include column A
2. Changed the column offsets to allow for the added column.





Option Explicit

Sub test1()
  Dim teste     As String
  teste = VLOOKUPNTH("castro", Range("A1:C22"), 3, 3)
  Debug.Print "Result: " & teste
End Sub

Function VLOOKUPNTH(lookup_value, table_array As Range, col_index_num As Integer, nth_value As Integer) As String

Dim nRow As Long
Dim nVal As Integer
Dim bFound As Boolean

    VLOOKUPNTH = "No Match"

    With table_array
        For nRow = 1 To .Rows.Count
            ' Must match both columns to be counted.
            If .Cells(nRow, 2).Value = lookup_value And .Cells(nRow, 1).Value = "a2" Then
                nVal = nVal + 1
            End If
            If nVal = nth_value Then
                ' Now we have found the nth occurence of the lookup value.
                VLOOKUPNTH = .Cells(nRow, col_index_num).Text
                Exit Function
            End If
        Next nRow
    End With
End Function