+ Reply to Thread
Results 1 to 2 of 2

find all instances of text in string

Hybrid View

  1. #1
    Dave B
    Guest

    find all instances of text in string

    I have a string in which I am searching for each instance of the text
    "begin*end", where * can be a string of any length. I want to extract each
    of these sequences out of the string. So I need a way to find all of them
    (doesn't InStr just find the first one?). Also, there is one complication:
    "begin" is not always the start of a string I need ... only when there is an
    "end" before another "begin". Any ideas? Thanks.



  2. #2
    Forum Moderator Leith Ross's Avatar
    Join Date
    01-15-2005
    Location
    San Francisco, Ca
    MS-Off Ver
    2000, 2003, & 2010
    Posts
    23,259
    Hello Dave,

    Provided that string you want to extract is always between the words "Begin" and "End" this macro will work. The case of the words is ignored in the search. A variable labeled Cnt is counter for the number of strings found. You can place additional code after this to what you want with the extracted string. If you have any questions or need help expanding the code, you can contact me via email LeithRoss@aol.com.

    Sub ExtractString()
    
      Dim Cnt As Long
      Dim NextIndex As Long
      Dim StartIndex As Long
      Dim StrPos As Long
      Dim ExtractStr As String
      
        SearchStr = "   Beginhere is my test string.end Beginnew test string.end"
        StartIndex = 1
        
        Do
          StrPos = InStr(StartIndex, SearchStr, "Begin", vbTextCompare)
            If StrPos < 1 Then
              Exit Do
            Else
              StartIndex = StrPos + 5
              NextIndex = InStr(StartIndex, SearchStr, "End", vbTextCompare)
                If NextIndex > 0 Then
                  ExtractStr = Mid(SearchStr, StartIndex, NextIndex - StartIndex)
                  Cnt = Cnt + 1
                End If
            End If
        Loop
        
    End Sub
    Sincerely,
    Leith Ross

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1