带替换变量的可自定义文本
一篇关于如何在 VBA 中使用带替换变量的文本模板的文章
引言
假设你需要向不同的收件人发送几封相似的电子邮件,并且需要使每封电子邮件都个性化。这段代码允许你将通用的文本模板转换为个性化版本,通过替换变量来实现。例如,对于以下模板:
Dear %Surname%, We would like to thank you for buying %Product% from us... ... 
It will be delivered on %DeliveryDate% ... 
发送给特定客户的具体文本将是:
Dear Smith, We would like to thank you for buying Big TV Set from us... ... 
It will be delivered on 20/11/2009 ... 
如以下代码所示,个性化是通过用 Access 中通过记录 ID、表名和主键字段找到的相关记录中的值替换用百分号 (%) 括起来的变量来实现的。
背景
该函数通常用于创建通知电子邮件,报告某些业务流程中的更新。最常用的替换变量示例包括流程名称、流程位置和所需的操作。
Using the Code
所有替换都由函数 MakeText$ 执行。该函数有 4 个参数:
- text$- 包含用百分号 (%) 括起来的替换变量的文本模板
- tableName$- 包含与文本模板中替换变量匹配的字段名称的 Access 表或视图的名称
- pkFieldName$- 存储主键的字段名称
- recordID$- 用于替换的值包含在该记录的主键
Public Function MakeText$(text$,tableName$,pkFieldName$, recordID$)
On Error GoTo Err
    ' Make Sql string
    Dim sql$
    Dim OriginalText$
    OriginalText$ = text
    Dim i As Integer
    Dim firstQual As Integer
    Dim secondQual As Integer
    Dim ToReplace As String
    i = 1
    ' Replace replacement variables with access fields
    Do While i < Len(text)
        If Mid(text, i, 1) = "%" Then
            firstQual = i
            secondQual = InStr(firstQual + 1, text, "%")
            ToReplace = Mid(text, firstQual + 1, secondQual - firstQual - 1)
            text$ = replace(text, "%" & ToReplace & "%",  _
        """ & " & tableName$ & "." & ToReplace & " & """)
            i = i + secondQual - firstQual + 13
        End If
        i = i + 1
    Loop
    Dim quotes$ ' Add quotes if ID is of string type
    If isnumeric(recordID$) Then
        quotes$=""
    Else: quotes$=""""
    End If
    ' Select specific text from source table (tableName)
    sql$ = "SELECT Left(""" & text$ & """,255) as NewText " & _
            "FROM " & tableName$ & "  WHERE " & pkFieldName$ & "=" & 
quotes$ & recordID$ & quotes$
    ' Open Recordset
    Dim rs As Recordset
    Set rs = CurrentDb.OpenRecordset(sql$)
    ' Get the text from the recordset
    If Not rs.EOF Then
        rs.MoveFirst
        ' Get New Text
        MakeText$ = rs![NewText].value
    Else: MakeText$ = OriginalText$
    End If
    rs.Close
    Set rs = Nothing
    Exit Function
Err: ' Oops
    MakeText$ = text$
    Set rs = Nothing
    MakeText$ = OriginalText$
End Function
要使用这段代码,首先保存你的文本模板,然后调用该函数。在我们的例子中,对于新客户史密斯先生,可能是:
...
newText$=MakeText$(templateText$, "NewCustomers", "ID", custID)
...
这里,templateText$ 是为新客户设计的电子邮件通知模板的文本,"NewCustomers" 是一个 Access 视图,其中包含新客户的记录,包括史密斯先生的记录,"ID" 是此视图中的主键字段,而 custID 是一个存储史密斯先生记录的实际 ID 的变量。
如果未找到记录,函数将返回原始模板文本。
限制:由于 Microsoft Access 在查询结果中字符串长度的限制,模板长度应小于 255 个字符。
兴趣点
此函数允许尽可能减少存储在系统中的文本模板数量。此外,它非常通用,可以在许多场合使用。
历史
- 2009 年 10 月 30 日:初始发布
- 2009 年 11 月 2 日:文章更新



