22 February 2018

String.Format function in VBA and VBScript

Public Function StringFormat(wFormat As String, ParamArray args()) As String
    
    Dim res As String
    Dim x As Long
    
    res = wFormat
    
    res = Replace(res, "\n", vbNewLine)
    res = Replace(res, "\t", vbTab)
    res = Replace(res, "\q", Chr(34))
    res = Replace(res, "\b", "•")    ' \b = Bullet
    
    For x = 0 To UBound(args)
        res = Replace(res, "{" & x & "}", Nz(args(x)))
    Next
    
    StringFormat = res
    
End Function

Usage example:
Debug.Print StringFormat("Hello {0}, it's {1}", "World", Now)
Returns:
Hello World, it's 22/02/2018 18:01:07




VBScript version, since VBScript doesn't allow ParamArray variables.
Note: "args" parameter could be a String or an Array()
Function StringFormat(wFormat, args)

    Dim res
    Dim x

    res = wFormat

    res = Replace(res, "\n", vbNewLine)
    res = Replace(res, "\t", vbTab)
    res = Replace(res, "\q", Chr(34))
    res = Replace(res, "\b", "•")    ' \b = Bullet

    if IsArray(args) Then
        For x = LBound(args, 1) To UBound(args, 1)
            res = Replace(res, "{" & x & "}", args(x))
        Next

    Else
        res = Replace(res, "{0}", args)

    End If

    StringFormat = res

End Function

Usage example:
wscript.echo StringFormat("Hello {0}", "World")
wscript.echo StringFormat("Hello {0}, it's {1}", Array("World", Now))

Returns:
Hello World
Hello World, it's 29/03/2018 11:58:54