35
Chapter 1 1 • Manipulating Strings
46
Replacing Numbered Tokens within a String
If you’re creating text resources that need to be translated to local languages, or if
you just need to replace a series of tokens in a string with a series of text strings,
the function shown in Listing 1.8 will help you out. This function allows you to
pass in a list of text strings to replace numbered tokens (%1, %2, and so on) in a
larger text string.
If you separate the text for your application from the application’s user inter-
face, it’s far easier to prepare the application for international use. However, it’s
inevitable that some of your strings will need to contain replaceable parameters.
Using dhTokenReplace makes it simple to perform those replacements at runtime.
For example, running the following fragment:
strText = dhTokenReplace("Unable to add file %1 to %2", _
"C:\AUTOEXEC.BAT", "C:\FOO.ZIP")
would place the text “Unable to add file C:\AUTOEXEC.BAT to C:\FOO.ZIP”
into strText. (The assumption here is that the resource string “Unable to add…” is
coming from a table, a resource file, or some other source external to your applica-
tion and is translated for use in countries besides your own.) But what if, in a par-
ticular language, the correct phrasing would be (translated back into English)
“C:\FOO.ZIP is unable to contain C:\AUTOEXEC.BAT”? In that case, the transla-
tor could modify the resource to be “%2 is unable to contain %1”, and your code
would still function correctly.
Even if you’re not producing internationalized applications, dhTokenReplace
will make your work simpler. Being able to replace multiple substrings in one
pass can make your applications run faster and certainly will make them code
faster.
Using ParamArray to Pass an Array of Parameters
Although the ParamArray construct has been available in the past few versions of VBA,
few programmers have run across it. It’s not used often, but when you need it, it’s indis-
pensable. In this case, being able to pass a virtually unlimited number of parameters to a
function makes it possible to write one function that can handle unlimited situations.
To use this feature, you declare your function to accept a ParamArray parameter, like this:
Public Function dhTokenReplace(ByVal strIn As String, _
ParamArray varItems() As Variant) As String