【问题标题】:Using RegExp to Replace Form Control Values into String in MSAccess在 MS Access 中使用 RegEx 将表单控件值替换为字符串
【发布时间】:2011-12-02 21:23:14
【问题描述】:

我在 Outlook 中使用 MS Access 表单中的值显示电子邮件。我希望用户能够修改消息模板而无需编辑代码,因此我尝试以纯文本格式创建模板。在文本格式中,我用 %% 包围表单控件名称。然后在 Access Form 的按钮 _Click 事件处理程序中,读入文本文件后,我使用了 RegExp 对象:

Dim re As New RegExp
re.Pattern = "(%%)([A-Za-z0-9]+)(%%)"
re.Global = True
msg = re.Replace(template, " "" & $2 & "" ")

将 (%%)([A-Za-z0-9]+)(%%) 替换为 " & $2 & "。希望这会从表单中获取控件的值。

然后我在 Outlook 中使用显示 msg

Dim objOutlook As Outlook.Application
Dim objEmail As Outlook.MailItem
Set objOutlook = CreateObject("Outlook.application")
Set objEmail = objOutlook.CreateItem(olMailItem)

With objEmail
    .To = emailAdd
    .body = msg
    .Display
End With

不幸的是,消息中显示的是“& controlName.value &”,而不是控件的值。此外,虽然 .Global 设置为 True,但仅替换第一个匹配项。

如何让 VBA 执行全局替换,并填写控件的值?

【问题讨论】:

  • 1) 消息是否由来自 MS Access 表单上多个控件的文本组成? 2) 什么是文本文件,它如何适应流程?
  • template 变量中包含什么?您是否将 controlName.value 错误地传递给 template 并用“”包围它?在您的第二个问题上,是否将 .multiline = True 添加到您的正则表达式帮助中?
  • template 包含从文本文件中读取的字符串,其中包含套用信函的文本。我试图传入 controlName.value,但这并没有什么不同。是的,multiline = true 解决了第二个问题。

标签: regex ms-access vba outlook


【解决方案1】:

认为您正在寻找类似于以下代码的内容。

Sub Tester()

Dim template As String, msg As String
Dim re As Object, matches As Object, match As Object


    Set re = CreateObject("vbscript.regexp")

    re.Pattern = "(%%)([A-Za-z0-9]+)(%%)"
    re.MultiLine = True
    re.Global = True

    template = "The %%TextBox1%% brown " & vbCrLf & _
                "jumped %%TextBox2%% the lazy dog"

    Set matches = re.Execute(template)
    For Each match In matches
        Debug.Print match, match.submatches(1)
        template = Replace(template, match, Me.Controls(match.submatches(1)))
    Next match

    MsgBox template

End Sub

我在 Excel 用户窗体中使用两个文本框控件“TextBox1”和“TextBox2”对此进行了测试

【讨论】:

  • 是的,Replace(template, match, Me.Controls(match.submatches(1))) 正是我想要的!
猜你喜欢
  • 1970-01-01
  • 2014-04-19
  • 2020-09-12
  • 2019-03-22
  • 2019-04-30
  • 2013-06-26
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多