Get Last Index


Home           Programming       Favorites      

Sometimes I encounter long strings such as:

file:///C:/Documents and Settings/rdahl/My Documents/My Web Sites/AutomationInformation/Programming/MicrosoftVBA/TopicIndex.htm

All I really want is the value after the last slash.

This function finds the position of the last slash.

Function GetLastIndexOf( _
ByVal strFind As String, _
ByVal strText As String) _
As Integer
  On Error GoTo errHandler1
  Dim i As Integer
  
  For i = Len(strText) - 1 To 0 Step -1
    If Mid(strText, i, 1) = strFind Then
      GetLastIndexOf = i
      Exit Function
    End If
  
  Next i
  
  'if it gets here,
  'it didn't find it.
  GetLastIndexOf = -1
  Exit Function
errHandler1:
   MsgBox _
   "Err.Number:      " & Err.Number & vbCrLf & _
   "Err.Description: " & Err.Description, _
   vbCritical, "GetQualifiedFileNames Function " & _
   "terminated because of Fatal Error."

End Function				

It could be called with:

Sub callGetLastIndexOf()
  Dim intLastIndex As Integer
  Dim strSearchFor As String
  Dim strSearchIn As String

  strSearchFor = "/"
  strSearchIn = _
  "file:///C:/Documents and Settings/rdahl" & _
  "/My Documents/My Web Sites" & _
  "/AutomationInformation" & _
  "/Programming/MicrosoftVBA/TopicIndex.htm"
  
  intLastIndex = GetLastIndexOf( _
  strSearchFor, strSearchIn)

End Sub			

intLastIndex has a value of 113 in this particular example.