vba extract text between brackets code example

Example: vba extract text between brackets

' Returns first text between pOpen and pClose (both can't contain "/" character...)
Function ExtractTag(pSource As String, pOpen As String, pClose As String)
    Dim startC As Long, endC As Long
    startC = InStr(1, pSource, pOpen) + Len(pOpen)
    endC = InStr(1, pSource, pClose)
    If startC > 0 And Len(pSource) - startC - (Len(pSource) - endC) > 0 Then
        ExtractTag = Mid(pSource, startC, _
      		Len(pSource) - startC - (Len(pSource) - endC))
    End If
End Function
' --------------------------------------------------------------------------------------
Sub TestMe()
    Debug.Print ExtractTag("Weather is [tag]fine[#tag].", "[tag]", "[#tag]")    ' fine
    Debug.Print ExtractTag("Value(banana).", "(", ")")                          ' banana
    Debug.Print ExtractTag("Value{banana}.", "{", "}")                          ' banana
End Sub

Tags:

Vb Example