获取与 VBA 范围内的一组值相匹配的特定行号

Get a specific row number that matches a set of values of range in VBA

我在 VBA 中需要一些帮助,我仍在努力研究如何从值列表中找到与来自不同工作表的 运行ge 的一组值相匹配的行号。

以下是我试过的代码。

 Sub findmyrow()

   Dim myrange As Range
   Dim myrow As Long
   Dim mysheet As Worksheet

   Set myrange = ThisWorkbook.Sheets("Sheet2").Range("A1:Z1")
   myrow = ThisWorkbook.Sheets("Sheet1").Range("A1:Z1000").Find(What:=myrange, LookIn:=xlValues).ROW

   Debug.Print myrow

 End Sub

当我 运行 代码时,它只匹配 'Sheet2' = A 第一列的值而不是 'A B' 与 [=25 列表中找到的结果=].

非常感谢您的帮助。我是这里的新手。非常感谢。

我不认为 find 可以完成这项工作,因为它只需要一个值就可以找到。

也许 Whosebug 上的 formula-masters 之一有更好的解决方案。

使用 VBA 你可以这样做:

Option Explicit

Public Sub test_getRow()

Dim rgFind As Range, rgLookup As Range

With ThisWorkbook
    Set rgFind = .Worksheets("Sheet2").Range("A1:Z1")
    Set rgLookup = .Worksheets("Sheet1").Range("A1:Z1000")
End With
    
Debug.Print getRow(rgFind, rgLookup)
    
End Sub


'This is the generic routine to find the row
Public Function getRow(rgFind As Range, rgLookup As Range) As Long

'First check the input ranges
If rgFind.Columns.Count > rgLookup.Columns.Count Then
    MsgBox "Number of columns of rgFind have to be less or equal to the number of columns of rgLookup.", vbExclamation
    Exit Function
    
ElseIf rgFind.Rows.Count > 1 Then
    MsgBox "rgFind has to be a single row.", vbExclamation
    Exit Function
End If

'use arrays of values to increase performance
Dim arrFind As Variant: arrFind = rgFind.Value
Dim arrLookup As Variant: arrLookup = rgLookup.Value

Dim rowL As Long
Dim colF As Long
Dim rowMatch As Long


For rowL = 1 To UBound(arrLookup, 1)
    'checking each row of the lookup range
    For colF = 1 To UBound(arrFind, 2)
        'now compare each value of the lookup row to each value of the find row
        If arrFind(1, colF) = arrLookup(rowL, colF) Then
            'if equal store current row
            rowMatch = rowL
        Else
            'if not reset rowMatch and exit for-loop as this row can't match anylonger
            rowMatch = 0
            Exit For
        End If
    Next
    If rowMatch > 0 Then Exit For   'we found the row
Next

getRow = rowMatch

End Function

匹配一行

Sub MatchRow()

    Dim lrg As Range: Set lrg = ThisWorkbook.Worksheets("Sheet2").Range("A1:Z1")
    Dim lData As Variant: lData = lrg.Value
    
    Dim srg As Range
    Set srg = ThisWorkbook.Worksheets("Sheet1").Range("A1:Z1000")
    Dim rCount As Long: rCount = srg.Rows.Count
    Dim cCount As Long: cCount = srg.Columns.Count
    Dim sData As Variant: sData = srg.Value
    
    Dim MyRow As Long, r As Long, c As Long
    
    For r = 1 To rCount
        If sData(r, 1) = lData(1, 1) Then
            For c = 2 To cCount
                If sData(r, c) <> lData(1, c) Then Exit For
            Next c
            If c > cCount Then MyRow = r: Exit For
        End If
    Next r
    
    Debug.Print MyRow
    
End Sub