【发布时间】:2020-11-07 07:07:33
【问题描述】:
我想在文档中找到一些字符串并以特定方式将它们全部格式化。我很困惑,因为它起作用了,然后就停止了工作,而不是格式化开始删除文本。我发誓我没有改变任何东西 :D :D :D。我至少不知道如果.... :)
任何人都可以在我的代码中看到任何问题吗?
编辑:好的,所以它在我第一次运行时工作,当我撤消文档中的更改并再次运行代码时,它会删除这些行......而且它似乎不在这段代码中,但在我的其他代码的某个地方。是否需要在此处包含某种或“重置”设置,以避免旧的运行代码干扰?
Sub SimpleReplace()
Dim markStrings(19) As String
markStrings(0) = "some text"
'....
markStrings(19) = "some other"
'mark the specific string to highlight them
Call HighlightWords(markStrings)
End Sub
这是我的功能
'highlight all the different texts in an array
Function HighlightWords(ByRef highlightStrings() As String)
Dim Words As Variant
For Each Words In highlightStrings
'Clear existing formatting and settings in Find feature.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
'set formating
With Selection.Find.Replacement.Font
.Bold = True
.TextColor.RGB = RGB(240, 130, 50)
.Italic = True
End With
'Cycle through document and find words in collection.
'Highlight words when found.
With Selection.Find
.Text = Words
.Forward = True
.Wrap = wdFindContinue
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
Next
End Function
提前致谢!
【问题讨论】:
-
尝试添加
Selection.Find.Replacement.Text = Words -
或者试试这里的代码:stackoverflow.com/questions/46142800/…
-
Selection.Find.Replacement.Text = 文字有效。但是这样一来,我总是用它自己替换文本,对吧。这不只是一种解决方法吗?
-
是的,它可能是。您可以尝试使用
ResetFindParameters从这里完全重置查找例如stackoverflow.com/questions/60750388/… -
您的选择是什么?我认为它在第一次和下一次迭代之间会发生变化。最好使用范围(例如,ActiveDocument.Range)。