Function RandomSubStrings(ByRef aString As String, Optional alwaysChoose As Long = -1)
Const LMark As String = "{"
Const RMark As String = "}"
Const ChoiceSep As String = "|"
Dim startChr As Long
Dim preString As String, bracketedString As String, postString As String
Dim Phrases As Variant
Dim Index As Long, MarkCount As Long
If Len(Replace(aString, LMark, vbNullString)) <> Len(Replace(aString, RMark, vbNullString)) Then RandomSubStrings = "missing {}": Exit Function
startChr = InStr(1, aString, LMark)
If startChr = 0 Then
Rem choose among options
Phrases = Split(aString, ChoiceSep)
If alwaysChoose < 1 Then
RandomSubStrings = Phrases(Int(Rnd() * (UBound(Phrases) + 1)))
Else
RandomSubStrings = Phrases(Application.Min(UBound(Phrases), alwaysChoose - 1))
End If
Exit Function
Else
For Index = startChr To Len(aString)
MarkCount = MarkCount + (Mid(aString, Index, 1) = RMark) - (Mid(aString, Index, 1) = LMark)
If MarkCount = 0 Then Exit For
Next Index
preString = Left(aString, startChr - 1)
bracketedString = Mid(aString, startChr + 1, Index - startChr - 1)
postString = Mid(aString, Index + 1)
RandomSubStrings = RandomSubStrings(preString & RandomSubStrings(bracketedString, alwaysChoose) & postString, alwaysChoose)
End If
End Function