Skip to content

Instantly share code, notes, and snippets.

@mattcan
Last active December 15, 2015 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattcan/5288156 to your computer and use it in GitHub Desktop.
Save mattcan/5288156 to your computer and use it in GitHub Desktop.
Works similar to String.Format in .NET. Takes in a string and fills in the {n} variables.
' Needs error checking and to handle more than just strings
' Usage:
' StringFormat("My {2} dogs are {0}, {3}, and {1}.", "Dumbo", "Tim", "3", "Marsha")
Function StringFormat(ByVal ParseTemplate As String, ByVal Arg As String, ParamArray Args() As Variant) As String
Dim lastItemIndex As Integer, combinedArgs() As Variant
' Combine the passed in arguments
If Not UBound(Args) < LBound(Args) Then
ReDim combinedArgs(0 To UBound(Args) + 1)
combinedArgs(0) = Arg
For j = 0 To UBound(Args)
combinedArgs(j + 1) = Args(j)
Next
Else
ReDim x(0 To 0)
combinedArgs(0) = Arg
End If
lastItemIndex = UBound(combinedArgs)
Dim Parsed As String
Parsed = ParseTemplate
Dim i As Integer
For i = 0 To lastItemIndex
If InStr(ParseTemplate, "{" & i & "}") Then
' you may or may not want the trim() here
Parsed = Replace(Parsed, "{" & i & "}", Trim(combinedArgs(i)))
End If
Next
StringFormat = Parsed
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment