VBA Word:在Word文档中插入文本之前找到文本



我想做的是一些简单的(也许)。我已经编写了一个查找方法来遍历文档。我已经找到值- ']'和插入值- '[('。在这两者之间可以有1到100之间的任何数字。

我的当前代码是:

Sub FindBracket()
Dim FindValue As String
Dim ReplaceValue As String
Dim oRange As Range
Set oRange = ActiveDocument.Range
FindValue = "]"
InsertValue = "(["
With oRange.Find
.Text = FindValue
.MatchWholeWord = False

Do While .Execute = True
If .Found Then
oRange.InsertBefore (InsertValue)
End If
oRange.Start = oRange.End
oRange.End = ActiveDocument.Range.End
Loop
End With
End Sub

find方法工作得很好,但是我需要修改。insertbefore方法。

示例我需要转换' Dummy text 1] '' Dummy text [(1] '但是从代码中我得到' Dummy text 1[(] ',我似乎不知道如何做到这一点,我只有Excel VBA只有以前的经验。

我将非常感谢您的帮助。

试试这个:

Sub FindBracket()
Dim FindValue As String
Dim ReplaceValue As String
Dim oRange As Range
Set oRange = ActiveDocument.Content
FindValue = "[0-9]@]"
InsertValue = "[(^&"    ' ^& - found number

With oRange.Find
.Text = FindValue
.Replacement.Text = InsertValue
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True      ' enabled regular expressions

.Execute Replace:=wdReplaceAll
End With
End Sub
Before:
Dummy text 1234]
Dummy text 4321]
Dummy text 0]
Dummy text 1]
After:
Dummy text [(1234]
Dummy text [(4321]
Dummy text [(0]
Dummy text [(1]

你只需要:

Sub FindBracket()
Application.ScreenUpdating = False
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "[0-9]@]"
.Replacement.Text = "[(^&"
.Forward = True
.Format = False
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub

实际上,你甚至不需要一个宏——这一切都可以通过GUI使用通配符查找/替换相同的F/R表达式来完成。