Find string in range and return its row number in Excel VBA

3.9k Views Asked by At

I have a UserForm with a ListBox (lbxNames) of names. On the spreadsheet, I have a range of names (rngNames).

I want to find the row number of the name picked in the ListBox in the list rngNames and assign it to varRowNum. I can get the ListBox choice OK, but don't know where to go from there.

1

There are 1 best solutions below

0
On

Solution: This worked for me.

Set TargetCell = Range("rngNames").Find(What:= ENTER_LISTBOXVALUE_HERE, _
    LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)
varRowNum = TargetCell.Row

In case you are looking for the relative row number within rngNames use this instead:

varRowNum = TargetCell.Row - Range("rngNames").Cells(1, 1).Row + 1

Result:

Absolute row number in worksheet: enter image description here

Relative row number in rngNames: enter image description here

Explanation: The .Find method will return a cell object of the first occurrence of the search term. The .Row property will give you the row number of the found cell within its worksheet. For the relative number, you can simply substract the row number of the first cell of the range (.Cells(1,1).Row) from the absolute row number.