Visual Basic for Applications中的文本模板引擎/功能

Mar*_*n K 4 excel vba excel-vba

我公司VBA的一个常见用法是根据Excel表格中输入的信息生成源代码.鉴于VBA的本机字符串操作,执行此操作的代码编写起来很繁琐,而且不易读取.

一个简单的例子(这些变得更复杂)是:

Print #fileIdentifier, SSpace(9) & "update_" & print_string & "[" & CStr(j) & "] <= 1'b0;"
Print #fileIdentifier, SSpace(9) & print_string & "_ack_meta" & "[" & CStr(j) & "] <= 1'b0;"
Print #fileIdentifier, SSpace(9) & print_string & "_ack_sync" & "[" & CStr(j) & "] <= 1'b0;"
Run Code Online (Sandbox Code Playgroud)

我在VBA中寻找一个允许我使用"文本模板"指定它的解决方案,因此定义一个看起来像这样的文本

    update_@name@[@bit@] <= 1'b0;
    @name@_ack_meta[@bit@] <= 1'b0;
    @name@_ack_sync[@bit@] <= 1'b0;
Run Code Online (Sandbox Code Playgroud)

并且有一个函数/方法调用,传递@ name @和@ bit @的值,用相应的值替换@ name @和@ bit @的所有实例.

Ale*_* K. 5

基本插入功能:

Function insert(template As String, ParamArray inserts() As Variant) As String
    Dim i As Long
    For i = 0 To UBound(inserts)
        template = Replace$(template, "%" & i + 1 & "%", inserts(i))
    Next

    '// some special cases perhaps
    template = Replace$(template, "%SSPACE%", SSpace(9))
    template = Replace$(template, "\r\n", VbCrLf)

    insert = template
End Function
Run Code Online (Sandbox Code Playgroud)

对于

?insert("Foo %1% Bar %2% Qux %3% (%1%)", "A", "B", "C")

Foo A Bar B Qux C (A)
Run Code Online (Sandbox Code Playgroud)

映射(添加对Microsoft Scripting Runtime的引用):

Dim col As New Scripting.Dictionary
col("name") = "bob"
col("age") = 35

MsgBox insert2("Hello %name% you are %age%", col)

...

Function insert2(template As String, map As Scripting.Dictionary) As String
    Dim name
    For Each name In map.Keys()
        template = Replace$(template, "%" & name & "%", map(name))
    Next
    insert2 = template
End Function
Run Code Online (Sandbox Code Playgroud)