Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA string interpolation syntax

Tags:

vba

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"

like image 382
Josh Petitt Avatar asked Jan 29 '15 17:01

Josh Petitt


People also ask

Is the syntax for string interpolation?

Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.

What is interpolation syntax?

The interpolation syntax is powerful and allows you to reference variables, attributes of resources, call functions, etc. You can also perform simple math in interpolations, allowing you to write expressions such as ${count. index + 1} .

How is string interpolation performed?

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.

What is string interpolation in VB net?

In visual basic, String Interpolation is a feature which is useful to embed any valid expression that returns a value into a string using $ operator. The string which is prepended with $ operator will call it as an interpolated string and this feature is available from the latest versions.


1 Answers

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.

like image 147
natancodes Avatar answered Sep 27 '22 21:09

natancodes