12

What is the VBA string interpolation syntax? Does it exist?

I would to to use Excel VBA to format a string. I have a variable foo that I want to put in a string for a range.

Dim row as Long
row = 1

myString = "$row:$row"

I would like the $row in the string to be interpolated as "1"

1
  • 1
    Why would not myString = "$" & row & ":$" & row suffice? Commented Jan 29, 2015 at 18:02

5 Answers 5

19

You could also build a custom Format function.

Public Function Format(ParamArray arr() As Variant) As String

    Dim i As Long
    Dim temp As String

    temp = CStr(arr(0))
    For i = 1 To UBound(arr)
        temp = Replace(temp, "{" & i - 1 & "}", CStr(arr(i)))
    Next

    Format = temp
End Function

The usage is similar to C# except that you can't directly reference variables in the string. E.g. Format("This will {not} work") but Format("This {0} work", "will").

Public Sub Test()

    Dim s As String

    s = "Hello"
    Debug.Print Format("{0}, {1}!", s, "World")
End Sub

Prints out Hello, World! to the Immediate Window.

2
  • Visiting from another question Looks like this is the best you can get for something that looks clean! Thanks for this! :)
    – Sancarn
    Commented Apr 7, 2017 at 20:15
  • Be careful using this as you will over-ride VBs built-in Format function. I suggest giving it a different name, e.g. CFormat. Commented Mar 27 at 11:35
13

This works well enough, I believe.

Dim row as Long
Dim s as String

row = 1
s = "$" & row & ":$" & row

Unless you want something similar to Python's or C#'s {} notation, this is the standard way of doing it.

2
  • sounds good, I was wanting interpolation, but it sounds like concatenation is my only choice, thanks for the quick answer! Commented Jan 29, 2015 at 18:05
  • This would call the string constructor 5 times would it not? In a loop with loots of iterations that could be quite slow? Commented Mar 11, 2021 at 21:41
5

Using Key\Value Pairs

Another alternative to mimic String interpolation is to pass in key\value pairs as a ParamArray and replace the keys accordingly.

One note is that an error should be raised if there are not an even number of elements.

' Returns a string that replaced special keys with its associated pair value.
Public Function Inject(ByVal source As String, ParamArray keyValuePairs() As Variant) As String

    If (UBound(keyValuePairs) - LBound(keyValuePairs) + 1) Mod 2 <> 0 Then
        Err.Raise 5, "Inject", "Invalid parameters: expecting key/value pairs, but received an odd number of arguments."
    End If

    Inject = source

    ' Replace {key} with the pairing value.
    Dim index As Long
    For index = LBound(keyValuePairs) To UBound(keyValuePairs) Step 2
        Inject = Replace(Inject, "{" & keyValuePairs(index) & "}", keyValuePairs(index + 1), , , vbTextCompare)
    Next index

End Function

Simple Example

Here is a simple example that shows how to implement it.

Private Sub testingInject()
    Const name As String = "Robert"
    Const age As String = 31
    Debug.Print Inject("Hello, {name}! You are {age} years old!", "name", name, "age", age)
    '~> Hello, Robert! You are 31 years old!
End Sub

Although this may add a few extra strings, in my opinion, this makes it much easier to read long strings.

See the same simple example using concatenation:

Debug.Print "Hello, " & name & "! You are " & age & " years old!"

Using Scripting.Dicitionary

Really, a Scripting.Dictionary would be perfect for this since they are nothing but key/value pairs. It would be a simple adjustment to my code above, just take in a Dictionary as the parameter and make sure the keys match.

Public Function Inject(ByVal source As String, ByVal data As Scripting.Dictionary) As String
    Inject = source

    Dim key As Variant
    For Each key In data.Keys
        Inject = Replace(Inject, "{" & key & "}", data(key))
    Next key
End Function

Dictionary example

And the example of using it for dictionaries:

Private Sub testingInject()
    Dim person As New Scripting.Dictionary
    person("name") = "Robert"
    person("age") = 31
    Debug.Print Inject("Hello, {name}! You are {age} years old!", person)
    '~> Hello, Robert! You are 31 years old!
End Sub

Additional Considerations

Collections sound like they would be nice as well, but there is no way of accessing the keys. It would probably get messier that way.

If using the Dictionary method you might create a simple factory function for easily creating Dictionaries. You can find an example of that on my Github Library Page.


To mimic function overloading to give you all the different ways you could create a main Inject function and run a select statement within that.

Here is all the code needed to do that if need be:

Public Function Inject(ByVal source As String, ParamArray data() As Variant) As String

    Dim firstElement As Variant
    assign firstElement, data(LBound(data))

    Inject = InjectCharacters(source)

    Select Case True
        Case TypeName(firstElement) = "Dictionary"
            Inject = InjectDictionary(Inject, firstElement)

        Case InStr(source, "{0}") > 0
            Inject = injectIndexes(Inject, CVar(data))

        Case (UBound(data) - LBound(data) + 1) Mod 2 = 0
            Inject = InjectKeyValuePairs(Inject, CVar(data))

        Case Else
            Err.Raise 5, "Inject", "Invalid parameters: expecting key/value pairs or Dictionary or an {0} element."
    End Select

End Function

Private Function injectIndexes(ByVal source As String, ByVal data As Variant)
    injectIndexes = source

    Dim index As Long
    For index = LBound(data) To UBound(data)
        injectIndexes = Replace(injectIndexes, "{" & index & "}", data(index))
    Next index
End Function


Private Function InjectKeyValuePairs(ByVal source As String, ByVal keyValuePairs As Variant)
    InjectKeyValuePairs = source

    Dim index As Long
    For index = LBound(keyValuePairs) To UBound(keyValuePairs) Step 2
        InjectKeyValuePairs = Replace(InjectKeyValuePairs, "{" & keyValuePairs(index) & "}", keyValuePairs(index + 1))
    Next index
End Function

Private Function InjectDictionary(ByVal source As String, ByVal data As Scripting.Dictionary) As String
    InjectDictionary = source

    Dim key As Variant
    For Each key In data.Keys
        InjectDictionary = Replace(InjectDictionary, "{" & key & "}", data(key))
    Next key
End Function

' QUICK TOOL TO EITHER SET OR LET DEPENDING ON IF ELEMENT IS AN OBJECT
Private Function assign(ByRef variable As Variant, ByVal value As Variant)
    If IsObject(value) Then
        Set variable = value
    Else
        Let variable = value
    End If
End Function

End Function

Private Function InjectCharacters(ByVal source As String) As String

    InjectCharacters = source

    Dim keyValuePairs As Variant
    keyValuePairs = Array("n", vbNewLine, "t", vbTab, "r", vbCr, "f", vbLf)

    If (UBound(keyValuePairs) - LBound(keyValuePairs) + 1) Mod 2 <> 0 Then
        Err.Raise 5, "Inject", "Invalid variable: expecting key/value pairs, but received an odd number of arguments."
    End If

    Dim RegEx As Object
    Set RegEx = CreateObject("VBScript.RegExp")
    RegEx.Global = True

    ' Replace is ran twice since it is possible for back to back patterns.
    Dim index As Long
    For index = LBound(keyValuePairs) To UBound(keyValuePairs) Step 2
        RegEx.Pattern = "((?:^|[^\\])(?:\\{2})*)(?:\\" & keyValuePairs(index) & ")+"
        InjectCharacters = RegEx.Replace(InjectCharacters, "$1" & keyValuePairs(index + 1))
        InjectCharacters = RegEx.Replace(InjectCharacters, "$1" & keyValuePairs(index + 1))
    Next index

End Function
1

I have a library function SPrintF() which should do what you need.

It replaces occurrences of %s in the supplied string with an extensible number of parameters, using VBA's ParamArray() feature.

Usage:
SPrintF("%s:%s", 1, 1) => "1:1"
SPrintF("Property %s added at %s on %s", "88 High St, Clapham", Time, Date) => ""Property 88 High St, Clapham added at 11:30:27 on 25/07/2019"

Function SprintF(strInput As String, ParamArray varSubstitutions() As Variant) As String

    'Formatted string print: replaces all occurrences of %s in input with substitutions

    Dim i As Long
    Dim s As String

    s = strInput

    For i = 0 To UBound(varSubstitutions)
        s = Replace(s, "%s", varSubstitutions(i), , 1)
    Next

    SprintF = s 

End Function

Just to add as a footnote, the idea for this was inspired by the C language printf function.

1

I use a similar code to that of @natancodes except that I use regex to replace the occurances and allow the user to specifiy description for the placeholders. This is useful when you have a big table (like in Access) with many strings or translations so that you still know what each number means.

Function Format(ByVal Source As String, ParamArray Replacements() As Variant) As String
    
    Dim Replacement As Variant
    Dim i As Long
    For i = 0 To UBound(Replacements)
        
        Dim rx As New RegExp
        With rx
            .Pattern = "{" & i & "(?::(.+?))?}"
            .IgnoreCase = True
            .Global = True
        End With
                
        Select Case VarType(Replacements(i))
            Case vbObject
                If Replacements(i) Is Nothing Then
                    Dim Matches As MatchCollection
                    Set Matches = rx.Execute(Source)
                    If Matches.Count = 1 Then
                        Dim Items As SubMatches: Set Items = Matches(0).SubMatches
                        Dim Default As String: Default = Items(0)
                        Source = rx.Replace(Source, Default)
                    End If
                End If
            Case vbString
                Source = rx.Replace(Source, CStr(Replacements(i)))
        End Select
        
    Next

    Format = Source

End Function

Sub TestFormat()

    Debug.Print Format("{0:Hi}, {1:space}!", Nothing, "World")
    
End Sub
4
  • 1
    So thing after the colon : is just a comment right?
    – Greedo
    Commented Oct 9, 2021 at 10:56
  • 1
    @Greedo it was supposed to be the default value in case no replacement was provided. I pasted the wrong code but I've updated it now.
    – t3chb0t
    Commented Oct 9, 2021 at 12:25
  • 1
    That's clever. FWIW Case vbString is overly restrictive, what if I pass a number? Could probably be Case Else and let VBA's implicit string casting decide what can be used. Also maybe using the special value Empty instead of Nothing could be more idiomatic, since this indicates the variable has not received an initial default value, which your function then sets
    – Greedo
    Commented Oct 10, 2021 at 10:23
  • @Greedo I agree with everything :-] I don't really like VBA so back then I didn't try to make it work for cases I didn't need.
    – t3chb0t
    Commented Oct 10, 2021 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.