Source code for Issue Number 61

Copyright 1997-2000 by C&D Programming Corp. All Rights Reserved. Source code may not be reproduced except for use in a compiled executable. All rights reserved. If you would like to reprint any or all of this code please email us at info@codeoftheweek.com

Code of the Week Home


Source Code

Just paste this source code into a module called basStrings and include it in your project.

'----------------------------------------------------------------------
'
'   Module Name:    basStrings
'   Written By:     C&D Programming Corp.
'   Create Date:    11/98
'   Copyright:      Copyright 1998 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'----------------------------------------------------------------------
Option Explicit

'
'   This function works just like Instr, but it searches
'   from the end of the string instead of the beginning
'
Public Function ReverseInstr(sStringToSearch As String, _
                                sStringToFind As String, _
                                Optional Compare As VbCompareMethod = vbBinaryCompare) As Long

    Dim bDone As Boolean
    Dim lStart As Long
    Dim lLastPos As Long

    lStart = 1
    lLastPos = 0
    bDone = False
    While Not bDone
        lLastPos = InStr(lStart, sStringToSearch, sStringToFind, Compare)
        If lLastPos <> 0 Then
            Debug.Print Mid(sStringToSearch, lLastPos) & " " & lStart & " " & lLastPos
            lStart = lLastPos + 1   ' start searching just past where the string was found
        Else
            lLastPos = lStart - 1 ' set the last position sStringToFind was found
            bDone = True        ' we are done since lLastPos was zero which means
                                ' the sStringToFind has no more matches.
        End If
    Wend
    ReverseInstr = lLastPos
End Function