我刚刚采取了VBA路线来自动完成今天的几天任务,所以请原谅,如果我听起来很天真我正试图打开一个word文档然后搜索一个表达突出(Bold)它,但我得到错误“用户定义的类型未定义“我能够打开word文档,但无法执行模式搜索。我已经收集了来自互联网的代码和代码,但它不起作用我正在使用Office 2013并添加了Microsoft VBscript参考文献中的Reg Ex 5.5。我搜索的模式是从“亲爱的”直到遇到的。干杯#GoingMad#
Sub Pattern_Replace()
Dim regEx, Match, Matches
Dim rngRange As Range
Dim pathh As String, i As Integer
pathh = "D:\Docs\Macro.docx"
Dim pathhi As String
Dim from_text As String, to_text As String
Dim WA As Object, WD As Object
Set WA = CreateObject("Word.Application")
WA.Documents.Open (pathh)
WA.Visible = True
Set regEx = New RegExp
regEx.Pattern = "Dear[^0-9<>]+)"
regEx.IgnoreCase = False
regEx.Global = True
Set Matches = regEx.Execute(ActiveDocument.Range.Text)
For Each Match In Matches
ActiveDocument.Range(Match.FirstIndex, Match.FirstIndex + Len(Match.Value)).Bold = True
Next
End Sub
你需要使用反斜杠在正则表达式中转义括号“)”:
regex.Pattern = "Dear[^0-9<>]+\)"
这是因为它在正则表达式中具有特定含义。
我个人也会将对Word-Range的引用分成几行:
Set rngRange = ActiveDocument.Range
rngRange.Expand Unit:=wdStory
Set Matches = regex.Execute(rngRange.Text)
虽然这不是必要的。
请考虑以下文本
亲爱的阿姨莎莉)我去了学校。
你的正则表达式模式将是"Dear[^)]+"
这个将包括括号。 Dear[\w\s]+\)
你不需要正则表达式 - Word中的通配符查找/替换将更有效地完成工作:
With WA.ActiveDocument.Range.Find
.ClearFormatting
.Text = "Dear[!\)]@\)"
.Replacement.ClearFormatting
.Replacement.Font.Bold = True
.Replacement.Text = "^&"
.Format = True
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With