使用RegExp将表格控件值替换为MSAccess中的字符串 [英] Using RegExp to Replace Form Control Values into String in MSAccess
问题描述
我正在使用MS Access表单中的值在Outlook中显示电子邮件.我希望用户能够在不编辑代码的情况下修改消息模板,因此我尝试以纯文本格式创建模板.在文本格式中,我将%%括在表单控件名称中.然后,在访问表单的按钮_Click事件处理程序中,读完文本文件后,我使用了RegExp对象:
I am displaying an email message in Outlook using values from an MS Access form. I would like users to have the ability to modify the message template without having to edit the code, so I am attempting to create templates in plain text format. In text format, I surround form control names with %%. Then in the button _Click event handler of an Access Form, after reading in the text file, I used a RegExp object:
Dim re As New RegExp
re.Pattern = "(%%)([A-Za-z0-9]+)(%%)"
re.Global = True
msg = re.Replace(template, " "" & $2 & "" ")
将(%%)([A-Za-z0-9] +)(%%)"替换为& $ 2&".希望这将从表格中获取控件的值.
to replace (%%)([A-Za-z0-9]+)(%%) with " & $2 & ". The hope was that this will grab the values of the controls from the form.
然后我使用以下方法在Outlook中显示味精
I then display msg in outlook using
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,但仅替换第一个匹配项.
Unfortunately, " & controlName.value & " shows in the message instead of the value of the control. Additionally, although .Global is set to True, only the first match is replaced.
如何让VBA执行全局替换并填写控件的值?
How can I get VBA to preform a global replace, and fill in the value of the controls?
推荐答案
我认为,您正在寻找类似以下代码的内容.
I think you're looking for something like the code below.
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
我在带有两个文本框控件"TextBox1"和"TextBox2"的Excel用户窗体中对此进行了测试
I tested this in an Excel userform with two textbox controls "TextBox1" and "TextBox2"
这篇关于使用RegExp将表格控件值替换为MSAccess中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!