Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

FormatMessage-like formatting in VBScript

0.00/5 (No votes)
11 Feb 2002 1  
A simple function to do FormatMessage-like formatting in VBScript

Overview

Recently I've been forced to do a lot of ASP coding using VBScript, and immediately I sorely missed the slot-based string formating functions available in most other languages.

In Python, for instance, you could do this:

result = "Hello %s! How are you this %s?" % (name, "morning")

Well, even more useful is to have named, or indexed, slots so you can do I18N without code changes, or reuse parameters without repeating them in the argument list. The SDK function FormatMessage does this for you if you are programming in a "real" language.

I decided to whip up a very simple FormatMessage look-alike for my own use. I'm sure most everybody coding in VBScript has done something similar. In case you haven't done so already, feel free to use this code. Enjoy!

Details

Well, here it is in all it's glory.

function Fmt(str, args)
    dim res
    res = str

    dim i
    for i = 0 to UBound(args)
        res = Replace(res, "%"&CStr(i+1)&"%", args(i))
    next

    res = Replace(res, "\n", vbCrLf)
    res = Replace(res, "\t", vbTab)

    fmt = res
end function

You call it like so:

str = Fmt("<%1%>This is a %2%</%1%>", Array("div", "test"))

That's all there is to it. You use slot markers numbered from 1 placed between %-signs, e.g. %1%. If you use more slots than you have arguments the extraneuos ones will simply be left in the string. The arguments are passed in an Array. Since VBScript only uses VARIANT-types, you can put anything in here and the script engine will do it's best to convert it to a string.

I also added the convenience of using \t and \n for Tab and NewLine respectively.

Postscript

This code is somewhat similar to an article posted by Uwe Keim a long time ago. My approach is considerably simpler and, I think, more efficient.

If you have any comments on this article, you can contact me at svenax@bredband.net.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here