我有以下代码,从技术上讲是一个嵌套循环
Dim compareRange As Range
Dim toCompare As Range
Dim rFound As Range
Dim cel As Range
Set compareRange = Worksheets("sheet2").Range("A2:A" & Lastrow3)
Set toCompare = Worksheets("sheet3").Range("A2:A" & Lastrow4)
Set rFound = Nothing
For Each cel In toCompare
Set rFound = compareRange.Find(cel)
如何在单独的工作表中找到值的哪一行?例如,如果AAAA在sheet3的第1行中,并且在sheet2的第5行中找到它,我如何检索第5行的值5?
答案 0 :(得分:1)
FIND
返回对单元格的引用。从该引用中,您可以访问单元格的所有属性,就像手动设置对它的引用一样。
使用FINDNEXT
或FINDPREVIOUS
移至找到的项目的下一个或上一个实例。
下面的代码显示了如何从每个找到的项目中返回各种值:
Sub Test()
Dim compareRange As Range
Dim toCompare As Range
Dim rFound As Range
Dim cel As Range
Dim FirstAddress As String
Dim LastRow3 As Long
Dim LastRow4 As Long
LastRow3 = 189: LastRow4 = 9
Set compareRange = Worksheets("sheet2").Range("A2:A" & LastRow3)
Set toCompare = Worksheets("sheet3").Range("A2:A" & LastRow4)
With compareRange
For Each cel In toCompare
'Find the first instance of cel.
Set rFound = .Find(cel)
'Check that rFound contains a value otherwise an error will occur when
'trying to return values from it.
If Not rFound Is Nothing Then
FirstAddress = rFound.Address
Do
With rFound
Debug.Print "Row: " & .Row & " - Col: " & .Column & _
" - Sheet: " & .Parent.Name & " - Book: " & .Parent.Parent.Name
End With
'Find the next instance of cel.
Set rFound = .FindNext(rFound)
Loop While FirstAddress <> rFound.Address
End If
Next cel
End With
End Sub
https://msdn.microsoft.com/VBA/Excel-VBA/articles/range-find-method-excel
https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/with-statement