【问题标题】:VBA MS Word formating specific strings - code delets them insteadVBA MS Word 格式化特定字符串 - 代码将它们删除
【发布时间】: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)。

标签: vba ms-word


【解决方案1】:

如果您使用范围对象而不是选择对象执行查找,则无需担心重置查找/替换属性,否则这些属性会持续存在并可能导致其他代码出现问题。此外,它的速度要快得多。您可以尝试改用以下版本的函数,看看是否有帮助。

Function HighlightWords(ByRef highlightStrings() As String)
    Dim Words As Variant
    Dim rng As Range
    
    For Each Words In highlightStrings
        Set rng = ActiveDocument.Content
        
        With rng.Find
            With .Replacement.Font
                .Bold = True
                .Color = RGB(240, 130, 50)
                .Italic = True
            End With
            .Execute Words, Replace:=wdReplaceAll
        End With
    Next
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多