VBA – String.Format or how to put variables in a string

C#, Python, Java and all the other “fancy” languages have a built-in method, which writes variables into a string. VBA does not have one. Depending on why do we need it, and if we can guarantee that no injection would be implemented to break something, there is an easy way to get what we need – simply replace the {i} with the next coming variable in the parameter array. Or with other words, if the idea is from the following mask:

“The quick {0} fox {1} over the lazy {2}.”

to get:

The quick brown fox jumps over the lazy dog.


StringFormat(sentence, "brown", "jumps", "dog")

then the function is actually quite a basic one (presuming no injections are going to be used):

This is a small sample, which illustrates the usage of the function:

At the end this is what we get in the immediate window:

Tagged with: , , , ,