'Find xlprevious code bringing up first record not last
Here is my code I've set up and is working as a vlookup. (I can follow this and I will understand it when I come back to it in 2 years.)
Sub lookup()
On Error GoTo ErrMsg
'turn whatever is in Site box to readable text
Dim sitevalue As String
sitevalue = Range("Site").Value
'turn whatever is in ID box to readable text
Dim lookfor As String
lookfor = Range("ID").Value
'find the last occurance of the ID number build within a set code so that the result is as a defined name so we can use it later on- result is a cell reference
Dim RC As Range
Set RC = Worksheets(sitevalue).Range("A:A").Find(lookfor, , , xlWhole, xlByRows, , xlPrevious)
'set searched for description result as definedname
Dim desc As String
desc = RC.Offset(0, 2).Value
'put description result in description box
Range("Description").Value = desc
'set searched for previous test result as definedname
Dim PTR As String
desc = RC.Offset(0, 21).Value
'put previous test result in description box
Range("PTR").Value = desc
'set searched for previous note result as definedname
Dim PN As String
desc = RC.Offset(0, 24).Value
'put previous test result in previous notes box
Range("PN").Value = desc
Exit Sub
ErrMsg:
MsgBox ("ID number not Found")
End Sub
When I set the search direction as xlPrevious
it brings up the first instance of the ID number. So in the picture below I put "AW002" into my search box and the code brings up the data in first row when it should be referencing the second row as that should have been what it came across first.
Solution 1:[1]
You need to supply the After
argument
With Range("A:A")
Set RC = .Find(what:=lookfor, after:=.Cells(1), lookat:=xlWhole, _
SearchOrder:=xlByRows, searchdirection:=xlPrevious)
End With
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Williams |