查找操作没有结果

时间:2014-11-21 11:21:35

标签: excel-vba vba excel

以下代码将表单A中的值与表单B匹配,其方式类似于Excel的VLOOKUP函数。

代码运行没有错误但是我没有得到单元格的结果。我该如何解决这个问题?

Sub LoopTem()

Dim ws As Worksheet
Dim ws1 As Worksheet
Dim i As Integer
Dim r As Integer
Dim lastRow1 As Integer
Dim lastRow2 As Integer

Set ws = Worksheets("Proactive Template")
Set ws2 = Worksheets("To")

lastRow1 = ws.Range("Q" & Rows.Count).End(xlUp).Row
lastRow2 = ws2.Range("Q" & Rows.Count).End(xlUp).Row

For i = 2 To lastRow1
    For r = 2 To lastRow2
        If ws.Cells(i, 18) = ws2.Cells(r, 17) Then
           ws.Cells(i, 20) = ws2.Cells(r, 19)
        Else
           ws.Cells(i, 20) = ""
        End If
    Next r

Next i


End Sub

1 个答案:

答案 0 :(得分:1)

当您找到匹配项后,您必须转到第20列中的下一个单元格。现在您不会这样做;因此,无论是否找到匹配项,搜索都会继续,并且最终会被ws.Cells(i, 20) = ""覆盖。

要在找到匹配项后停止搜索,请使用Exit For

    If ws.Cells(i, 18) = ws2.Cells(r, 17) Then
       ws.Cells(i, 20) = ws2.Cells(r, 19)
       Exit For ' <~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Stop search, iterate to next cell
    Else
       ws.Cells(i, 20) = "" ' <~~~~~~~~ Otherwise this will overwrite it eventually
    End If