VBA字符串插值语法

时间:2015-01-29 17:53:35

标签: vba

什么是VBA字符串插值语法?它存在吗?

我想使用Excel VBA格式化字符串。 我有一个变量foo,我想把它放在一个范围的字符串中。

Dim row as Long
row = 1

myString = "$row:$row"

我希望将字符串中的$行插值为“1”

5 个答案:

答案 0 :(得分:7)

您还可以构建自定义Format功能。

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

用法类似于C#,但您不能直接引用字符串中的变量。例如。 Format("This will {not} work")Format("This {0} work", "will")

Public Sub Test()

    Dim s As String

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

Hello, World!打印到立即窗口。

答案 1 :(得分:5)

我认为这很有效。

Dim row as Long
Dim s as String

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

除非您想要类似于Python或C#的{}符号,否则这是执行此操作的标准方法。

答案 2 :(得分:1)

我创建了一个自定义函数,该函数允许使用几种不同的方法在VBA中进行字符串插值。它允许您传入Array,Collection,Dictionary或ParamArray。

使用字典,实际上您也可以传递变量,因为它们具有键!

Public Function StringInterpolation(ByRef Source As String, ParamArray Args() As Variant) As String

    '@AUTHOR: ROBERT TODAR
    '@REQUIRED: REFERENCE TO MICROSOFT SCRIPTING RUNTIME (SCRIPTING.DICTIONARY)
    '@EXAMPLE: StringInterpolation("${0}\n\t${1}", "First Line", "Tab and Second Line")

    'USE REGULAR EXPRESSION REPLACE SPECIAL CHARATERS (NEWLINE, TAB)
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
    With regEx
        .Global = True
        .Pattern = "(^|[^\\])\\n"
        Source = .Replace(Source, "$1" & vbNewLine)
        .Pattern = "(^|[^\\])\\t"
        Source = regEx.Replace(Source, "$1" & vbTab)
    End With

    'REPLACE ${#} WITH VALUES STORED IN VARIABLE.
    Dim Index As Integer
    Select Case True

        Case TypeName(Args(0)) = "Dictionary":

            Dim Dict As Scripting.Dictionary
            Set Dict = Args(0)
            For Index = 0 To Dict.Count - 1
                Source = Replace(Source, "${" & Dict.Keys(Index) & "}", Dict.Items(Index), , , vbTextCompare)
            Next Index

        Case TypeName(Args(0)) = "Collection":
            Dim Col As Collection
            Set Col = Args(0)
            For Index = 1 To Col.Count
                Source = Replace(Source, "${" & Index - 1 & "}", Col(Index), , , vbTextCompare)
            Next Index

        Case Else:

            Dim Arr As Variant
            If IsArray(Args(0)) Then
                Arr = Args(0)
            Else
                Arr = Args
            End If

            For Index = LBound(Arr, 1) To UBound(Arr, 1)
                Source = Replace(Source, "${" & Index & "}", Arr(Index), , , vbTextCompare)
            Next Index

    End Select

    StringInterpolation = Source

End Function

以下是一些调用它的示例。

Private Sub ExamplesOfStringInterpolation()

    'Dictionaries are the best to use, since you can use the keys!!
    Dim Dict As Object
    Set Dict = CreateObject("Scripting.Dictionary")
    Dict("name") = "Robert"
    Dict("age") = 29
    Debug.Print StringInterpolation("Hello, my name is ${name}\nand I am ${age} years old", Dict)

    'Collection example
    Dim Col As New Collection
    Col.Add "Robert"
    Col.Add 29
    Debug.Print StringInterpolation("Hello, my name is ${0} and I am ${1} years old", Col)

    'Array example
    Dim Arr As Variant
    Arr = Array("Robert", 29)
    Debug.Print StringInterpolation("Hello, my name is ${0} and I am ${1} years old", Arr)

    'Passing Variables into the parameters (A cool and fast way of doing it!)
    Debug.Print StringInterpolation("Hello, my name is ${0} and I am ${1} years old", "Robert", 29)

End Sub

有关更多示例,请参见https://github.com/todar/VBA-Functions

答案 3 :(得分:0)

我有一个库函数SPrintF()可以满足您的需求。

它使用VBA的ParamArray()功能用可扩展的参数替换提供的字符串中%s的出现。

用法:
SPrintF(“%s:%s”,1,1)=>“ 1:1”
SPrintF(“属性%s在%s上的%s上添加”,“ 88 High St,Clapham”,时间,日期)=>“”“” Property 88 High St,Clapham于25/07/2019添加于11:30:27 ”

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

只需添加一个脚注,其想法便受到C language printf function的启发。

答案 4 :(得分:0)

我使用与@natancodes类似的代码,除了使用正则表达式替换出现的内容并允许用户为占位符指定 description 。当您有一个包含许多字符串或翻译的大表(例如在Access中)时,这很有用,这样您仍然知道每个数字的含义。

Function Format(ByVal source As String, ParamArray values() As Variant) As String
    
    Dim i As Long
    For i = 0 To UBound(values)
    
        Dim rx As New RegExp
        With rx
            .Pattern = "{" & i & "(:.+?)?}"
            .IgnoreCase = True
            .Global = True
        End With
        
        source = rx.Replace(source, CStr(values(i)))
    Next

    Format = source

End Function

Sub TestFormat()

    Debug.Print Format("{0:Hi}, {1:space}! --> {0}", "Hello", "World")
    
End Sub