2014-02-26 47 views
1

循環遍歷一個工作表a1:a和a如果在工作表2中列匹配a2:a然後在工作表1中找到偏移b2:b如果找到其他未找到。我已經編寫了一些代碼,但可能讓我自己感到困惑。我正在尋找清晰的答案。通過單元格循環查找列b內的匹配

Dim r1 As Range 
Dim r2 As Range 
Dim i As Integer 
Dim lookupArray As Variant 
Dim lookupVal As Variant 
Dim matchResult As Variant 
Dim rowIndex As Long 
Dim e1 As Integer 
Dim e2 As Integer 

    r1 = r1.Range("A2:A").Cells 
    r2 = r2.Range("B2:B").Cells 

    e1 = Cells(Rows.Count, "A").End(xlUp).Row 'Range("A" & Cells.Rows.Count).End(xlUp).Offset(1,0).Select 
    e2 = Cells(Rows.Count, "B").End(xlUp).Row 

      For rowIndex = r1 To e1 
      Set lookupVal = Range(r2 & rowIndex) 

      matchResult = Application.match(lookupVal, r1, 0) 

      If r1.cell(i, 1).Value = r2.cell(i, 1).Value And Not IsEmpty(Cells(i, 1).Value) Then 
        r1(i, 1).Offset(0, -1).Value "Found" 
        Else 
        r1(i, 1).Offset(0, -1).Value "NotFound" 
        End If 
       'copy found cells in sheet 3 
      Next rowIndex 

回答

0

First方法(更快,simplier和更短):

Sub test() 
    Dim lastrow As Long 

    'change Sheet1 to suit 
    With ThisWorkbook.Worksheets("Sheet1") 
     lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 
     With .Range("B2:B" & lastrow) 
      'change Sheet2 to suit 
      .Formula = "=IF(ISERROR(MATCH(A2,'Sheet2'!A:A,0)),""NotFound"", ""Found"")" 
      .Value = .Value 
     End With 
    End With 

End Sub 

第二種方法:

Sub test2() 
    Dim r1 As Range 
    Dim r2 As Range 
    Dim cell As Range 
    Dim lastrow As Long 

    'change Sheet1 to suit 
    With ThisWorkbook.Worksheets("Sheet1") 
     lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 
     Set r1 = .Range("A2:A" & lastrow) 
    End With 

    'change Sheet2 to suit 
    With ThisWorkbook.Worksheets("Sheet2") 
     lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 
     Set r2 = .Range("A2:A" & lastrow) 
    End With 

    For Each cell In r1 
     If IsError(Application.Match(cell, r2, 0)) Then 
      cell.Offset(, 1) = "NotFound" 
     Else 
      cell.Offset(, 1) = "Found" 
     End If 
    Next cell 

End Sub 
相關問題