循环通过列工作表1 a2:a并且如果theres在工作表2列a2中匹配:则在工作表1中找到的偏移量b2: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 :(得分:0)
第一种方法(更快,更简单,更短):
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