在迭代列时匹配单元格对,然后返回一对新单元格

时间:2015-02-16 15:27:19

标签: excel-vba if-statement for-loop excel-formula pattern-matching

我正在尝试编写一个代码,它将占用一个单元格然后遍历另一个列来查找匹配项,一旦找到匹配项,它将匹配同一行中的另外两个单元格并返回第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

1 个答案:

答案 0 :(得分:0)

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

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

我认为范围的默认属性是“值”但是尝试将.Value放到所有这些Cell行的末尾...就像你有一半的那样:)

[EDIT /增加:

...如果不这样做,你实际上并没有在任何时候搜索整个专栏:尝试类似:

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更快更好,