Forum Discussion

aawve's avatar
aawve
Copper Contributor
Nov 11, 2019
Solved

Extracting substrings from brackets

Hi, I'm working with a large dataset based on journal entry character strings. I have standardized names coded into the strings to allow easier reference for an analysis. An example below (not real ...
  • JKPieterse's avatar
    Nov 11, 2019

    aawve This User Defined Function does the trick:

    Function ExtractNames(TextWithNames) As String
        Dim Pos As Long
        Dim Ct As Long
        Dim BracketStart As Long
        Dim Result As String
        Dim WithInBrackets As Boolean
        If TypeName(TextWithNames) = "Range" Then
            TextWithNames = TextWithNames.Value
        End If
        Pos = InStr(TextWithNames, "[")
        If Pos <> 0 Then
            WithInBrackets = True
            BracketStart = Pos
            For Ct = Pos To Len(TextWithNames)
                If WithInBrackets Then
                    If Mid(TextWithNames, Ct, 1) = "]" Then
                        WithInBrackets = False
                        Result = Result & Mid(TextWithNames, BracketStart + 1, Ct - BracketStart - 1)
                        Result = Result & ","
                    End If
                ElseIf Mid(TextWithNames, Ct, 1) = "[" Then
                    WithInBrackets = True
                    BracketStart = Ct
                End If
            Next
        End If
        If Len(Result) > 0 Then Result = Left(Result, Len(Result) - 1)
        ExtractNames = Result
    End Function
    

Resources