我正在处理一个宏,它将循环遍历我的Word文档,并选择所有XE代码进行解析。
我正在尝试使用Find
获取所有此类文本,但我的正则表达式搜索根本无效。
我尝试过:</{ XE*/}>
,<{*XE*}>
无济于事。
提醒一下,文字将如下所示:
{ XE "Superhero - means a person with some powers" }
{ XE "Mountain is a tall hill, not always climbable." }
{ XE "Hill is a smaller mountain; not always large." }
我想遍历其中的每一个,并在找到每个;
后添加两个字符。如何使用RegEx找到这些?
编辑:出于某种原因,.Find
永远不会执行,即使使用以下代码:
Sub escape_Special_Characters_in_XE_Text()
Dim regExSearch$
Dim doc As Word.Document
Dim rngDoc As Word.Range, rngXE As Word.Range, rng As Word.Range
Dim bFound As Boolean
Dim iFieldCodeBegin&
Set doc = ActiveDocument
Set rngDoc = doc.Content
Set rngXE = rngDoc.Duplicate
bFound = True
iFieldCodeBegin = 6 '?
rngDoc.Find.ClearFormatting
With rngDoc.Find
.Text = "^d XE"
'.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
rngDoc.Find.Execute
rngDoc.Select ' This selects the whole document for some reason?
End Sub
关于我的文件,我有什么东西可以忽略吗?为什么它找不到任何东西。如果我录制一个宏,它使用Selection
而不是变量,但我可以一遍又一遍地运行它。当我尝试使用变量时,它似乎与我不同意。
答案 0 :(得分:4)
实际上,您可以通过指定ESC组合使用Word查找找到字段代码的起始括号:^d
当Find选取一个字段的起点时,整个字段都包含在Selection / Range中。因此,您可以沿着以下行循环文档中的所有XE字段:
Sub LoopAllXE()
Dim doc As word.Document
Dim rngDoc As word.Range
Dim rngXE As word.Range
Dim bFound As Boolean
Dim iFieldCodeBegin As Long
'Initialization
Set doc = ActiveDocument
Set rngDoc = doc.content
Set rngXE = rngDoc.Duplicate
bFound = True
iFieldCodeBegin = 6
With rngDoc.Find
.ClearFormatting
.ClearAllFuzzyOptions
.Text = "^d XE"
.Format = False
.wrap = wdFindStop
End With
'Get the XE fields' content
Do While bFound
bFound = rngDoc.Find.Execute
If bFound Then
Set rngXE = rngDoc.Duplicate
'Do something with the XE field content
'Below, the content is being trimmed of field code info
Debug.Print Mid(rngXE.Text, iFieldCodeBegin, _
Len(rngXE) - iFieldCodeBegin - 1)
'Content in table cells needs to be processed differently
'in order to avoid looping endlessly on the first "found"
Do While rngDoc.Information(wdWithInTable) And bFound
rngDoc.Collapse wdCollapseEnd
'Remainder of cell content after XE-field
rngDoc.End = rngDoc.Cells(1).Range.End - 1
bFound = rngDoc.Find.Execute
Set rngXE = rngDoc.Duplicate
'Do something with the XE field content
'May make sense to put this in a separate procedure
Debug.Print Mid(rngXE.Text, iFieldCodeBegin, _
Len(rngXE) - iFieldCodeBegin - 1)
If Not bFound Then
rngDoc.MoveStart wdCell, 1
End If
Loop
rngDoc.Collapse wdCollapseEnd
rngDoc.End = doc.content.End
End If
Loop
End Sub