匹配单元格对,同时遍历列然后 return 一对新单元格

Matching pairs of cells while iterating through columns to then return a new pair of cells

我正在尝试编写一个代码,它将获取一个单元格,然后遍历另一列以找到匹配项,一旦找到匹配项,它将匹配同一行中的其他两个单元格,return 第 5 个和第 6 个单元格的值。但是,它不起作用!有什么建议吗??

Sub rates()

Dim i As Integer

For i = 2 To 2187

        If Cells(i, 1).Value = Cells(i, 11).Value Then
            If Cells(i, 2).Value = Cells(i, 12).Value Then
                Cells(i, 20) = Cells(i, 1).Value
                Cells(i, 21) = Cells(i, 11).Value
                Cells(i, 22) = Cells(i, 4).Value
                Cells(i, 23) = Cells(i, 16).Value
            Else
                Cells(i, 24) = "No match"
            End If
        End If
Next i
End Sub

尝试完全限定您的单元格对象,即 sheet1.cells(i,1).value 等或包含在 with 语句中,即

with sheet1
   if .cells(i,X) = .cells(i,Y) then
   '...etc
end with

我认为一个范围的默认 属性 是 "Value" 但也尝试将 .Value 放在所有这些单元格行的末尾......就像你对其中一半所做的那样:)

[EDIT/Addition:]

...如果失败,您实际上并没有在任何时候搜索整列:尝试类似的方法:

Sub rates()

    Dim i As Integer
    Dim rgSearch As Range
    Dim rgMatch As Range
    Dim stAddress As String
    Dim blMatch As Boolean

    With wsSheet
        Set rgSearch = .Range(.Cells(x1, y1), .Cells(x2, y2)) ' Replace where appropriate (y = 1 or 11 i guess, x = start and end row)
    End With

    For i = 2 To 2187
        Set rgMatch = rgSearch.Find(wsSheet.Cells(i, y)) ' y = 1 or 11 (opposite of above!)
        blMatch = False

        If Not rgMatch Is Nothing Then
            stAddress = rgMatch.Address             

            Do Until rgMatch Is Nothing Or rgMatch.Address = stAddress
                If rgMatch.Offset(0, y).Value = Cells(i, 12).Value Then
                    Cells(i, 20) = Cells(i, 1).Value
                    Cells(i, 21) = Cells(i, 11).Value
                    Cells(i, 22) = Cells(i, 4).Value
                    Cells(i, 23) = Cells(i, 16).Value
                    blMatch = True
                Else

                End If

                Set rgMatch = rgSearch.FindNext(rgMatch)
            Loop


        End If
        If Not blMatch Then
            Cells(i, 24) = "No match"
        End If
    Next i
End Sub   

我在那里做了很多假设,您必须替换一些变量。你也可以使用 application.worksheetfunction.match 但 .find 更快更棒