在 MS Word 2010 中查找和替换整个文档中的文本(包括表格) [英] To find and replace a text in the whole document in MS Word 2010 (including tables)
问题描述
我有一个包含表格的 MS Word 文档.我正在尝试使用以下代码通过 VBA 查找和替换文本:
I have an MS Word document including a table. I am trying to find and replace text via VBA using the following code:
If TextBox1.Text <> "" Then
Options.DefaultHighlightColorIndex = wdNoHighlight
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = "<Customer_Name>"
.Replacement.Text = TextBox1.Text
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.ClearFormatting
With Selection.Find.Font
.Italic = True
End With
Selection.Find.Replacement.ClearFormatting
With Selection.Find.Replacement.Font
.Italic = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End If
这适用于替换我在表格外部的所有内容.但它不会替换表格中的任何内容.
This works fine for replacing all my content which is outside of the table. But it will not replace any of the content within the table.
推荐答案
如果您的目标是在整个文档中执行替换(从代码中看起来是这样,但并不明确),我建议您使用 Document.Range
而不是 Selection
对象.使用 Document.Range
将确保所有内容都被替换,即使在表格中也是如此.
If your goal is to perform replacements in the whole documents (it looks so from the code, but it is not explicit), I would suggest you use Document.Range
instead of the Selection
object. Using Document.Range
will make sure everything is replaced, even inside tables.
此外,它对用户更透明,因为光标(或选择)不会被宏移动.
Also, it is more transparent to the user, as the cursor (or selection) is not moved by the macro.
Sub Test()
If TextBox1.Text <> "" Then
Options.DefaultHighlightColorIndex = wdNoHighlight
With ActiveDocument.Range.Find
.Text = "<Customer_Name>"
.Replacement.Text = TextBox1.Text
.Replacement.ClearFormatting
.Replacement.Font.Italic = False
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End If
End Sub
这篇关于在 MS Word 2010 中查找和替换整个文档中的文本(包括表格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!