Johnny C
Well-known Member
- Joined
- Nov 7, 2006
- Messages
- 1,069
- Office Version
- 365
- Platform
- Windows
Hi
I've a function 'piece' that extracts text from between 2 delimiters in a string. E.g. text = "123-abc-567", piece(text,"-",2)="abc"
It currently goes through character by character looking for the delimiters.
Some time ago, someone mentioned on here that there was a function in XL2007 VBA that did it without the character loop.
I assume it's not worksheetfunction.find; can anyone tell me what it is?
(here's my code)
I've a function 'piece' that extracts text from between 2 delimiters in a string. E.g. text = "123-abc-567", piece(text,"-",2)="abc"
It currently goes through character by character looking for the delimiters.
Some time ago, someone mentioned on here that there was a function in XL2007 VBA that did it without the character loop.
I assume it's not worksheetfunction.find; can anyone tell me what it is?
(here's my code)
Code:
Function piece(Searchstring As String, Separator As String, IndexNum As Integer) As String
Dim i, SepCount, SepLen, StartPos, EndPos As Integer
Dim TestStr As String
SepLen = Len(Separator)
SepCount = 0
StartPos = 0
EndPos = 0
For i = 1 To Len(Searchstring) - (SepLen - 1)
TestStr = Mid(Searchstring, i, SepLen)
If TestStr = Separator Then
SepCount = SepCount + 1
If SepCount = IndexNum - 1 Then StartPos = i + 1
If SepCount = IndexNum Then EndPos = i
End If
Next i
If StartPos = 0 And EndPos = 0 Then
piece = ""
Exit Function
End If
If StartPos = 0 Then StartPos = 1
If EndPos = 0 Then EndPos = Len(Searchstring) + 1
piece = Mid(Searchstring, StartPos, EndPos - StartPos)
End Function