简体   繁体   中英

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

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.

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: 在此处输入图片说明

Relative row number in rngNames : 在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM