This type of function has probably been coded and posted several times, I'm not sure. But I wrote it anyway and I added a little extra bit into it that might interest some folks, especially if you're just getting started in VB ;D
This function will find the string data between 2 other strings:
VB Code:
Public Function strFindBetween(strToSearch As String, strStartPoint As String, strEndPoint As String, Optional skipInstance As Integer = 0) As String 'Quit the function if infomation provided doesn't fit requirements If strToSearch = "" Or strStartPoint = "" Or strEndPoint = "" Then Exit Function If Not InStrB(strToSearch, strStartPoint) > 0 And InStrB(strToSearch, strEndPoint) > 0 Then Exit Function Dim trimStrLine As String Dim strResult As String Dim skipInst As Integer trimStrLine = strToSearch 'Skip instances of first string; default doesn't skip For skipInst = 0 To skipInstance trimStrLine = Mid$(trimStrLine, InStr(trimStrLine, strStartPoint) + Len(strStartPoint)) Next skipInst 'Trim the line to the end of the second specified string trimStrLine = Mid$(trimStrLine, 1, InStr(trimStrLine, strEndPoint) - 1) 'Assign the string between the two given string-points strFindBetween = trimStrLine End Function
For example, if you had the string:
"Hi, my name is Brendan Davis" and you set strStartPoint to "my " and the strEndPoint to " Davis", the function would return the string between those two words(ie. "name is Brendan").
The kicker is that you can skip the starting point string however many times you wish. Using the skipInstance, if you had the string:
"Hi! My name is Brendan. My last name is Davis."
...and you set the strStartPoint to "My " and the strEndPoint to " Davis", and you set the skipInstance to 1(it defaults at 0), then it would skip over the phrase "My " the first time and go to the next instance of that phrase. Thus, the result in this case would yield:
"last name is"
Here's an example of how to call the function:
VB Code:
Dim strSrch as String strSrch = strFindBetween("Hello, my name is Brendan", "my ", "Brendan") 'This will cause strSrch to equal "name is"
..and how to call the function to skip an instance:
VB Code:
Dim strSrch as String strSrch = strFindBetween("The stove is still on. The house could catch fire!", "The ", "fire", 1) 'This will cause strSrch to equal "house could catch" because it would skip the first "The" instance
Enjoy, I guess!





Reply With Quote