I have an array of names stored in column a in Sheet 2. Say John, Smith, Bob, Peter, William. I need to check a cell in Sheet 1 and see what name is comes last in that cell.
Suppose the content in Sheet1, A1 is "William came home early. Smith rang the bel and Bob opened the door to see if that was Peter". In this, my requirement are, which all names contained in this sentence in A1 cell and whose name came last in this. Obviously it's Peter and I need it to be returned using vba.
I have written a macro using InStrRev function and using MyNames array which contains the names. However it searches the name in array in descending order only.
InStrRev(Range("t" & r).Value, MyNames(t), -1, vbTextCompare)
You could use a function to return the last used name.
The function works as a Worksheet function or VBA as it returns a String(name)
Function LastUsedName(rng As Range) As String
Dim names As Variant
names = Sheets(2).Range("A1:A" & Sheets(2).Range("A" & Rows.Count).End(xlUp).Row)
Dim cell As Range, i As Long, j As Long
Dim arr As Variant
arr = Split(rng, Chr(32))
For j = UBound(arr) To LBound(arr) Step -1
For i = LBound(names) To UBound(names)
If names(i, 1) = arr(j) Then
LastUsedName = names(i, 1)
Exit Function
End If
Next i
Next j
End Function
so
Sheet1 cell A1
Sheet2 column A
if you stick the function name in any cell then
you need to store the return value from that function somewhere, and then return the value that corresponds to the last position.
I'm assuming you're using t
to loop through the names.
add in these lines:
dim BigPos as long
dim BigLoc as long
dim CurrentPos as long
then alter your loop to actually remember which was the name it found furthest along the string
BigPos=0
BigLoc=0 ' set to zero, so no old checks can be found
for t=lbound(MyNames) to ubound(MyNames)
currentpos=InStrRev(Range("t" & r).Value, MyNames(t), -1, vbTextCompare)
if currenpos>bigpos then
'found one of the names *and*
'it's further along than the previous found name
bigpos=currentpos 'remember where in the string we found the text
bigloc=t 'and remember which name
end if
next t 'check them all, so there's no exit out of the for loop
then you can display the result:
if bigloc=0 then
msgbox "No names found"
else
msgbox "Name " & MyNames(bigloc) & " found at character " & bigpos
end if
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.