Find the text before, between, and after two target strings

Started by nandagopal, Nov 06, 2008, 04:15 PM

Previous topic - Next topic

nandagopal

Subroutine DivideText searches a string for two targets. It returns the text before the first target, between the two targets, and after the second target.


' Divide the text into pieces before, between, and after
' two targets.
Private Sub DivideText(ByVal txt As String, ByVal target1 _
    As String, ByVal target2 As String, ByRef before As _
    String, ByRef between As String, ByRef after As String)
Dim pos As Long

    ' Get the text before target1.
    pos = InStr(txt, target1)
    If pos = 0 Then
        ' target1 is missing. Set before = "".
        before = ""
    Else
        ' Set before.
        before = Left$(txt, pos - 1)

        ' Remove up to target1 from the string.
        txt = Mid$(txt, pos + Len(target1))
    End If

    ' Get the text before target2.
    pos = InStr(txt, target2)
    If pos = 0 Then
        ' target2 is missing. Set between = "".
        between = ""
    Else
        ' Set between.
        between = Left$(txt, pos - 1)

        ' Remove up to target2 from the string.
        txt = Mid$(txt, pos + Len(target2))
    End If

    ' Return what remains.
    after = txt
End Sub