【问题标题】:Search all open documents, find text, and delete to the end of the document Word Macro搜索所有打开的文档,查找文本,删除到文档末尾 Word 宏
【发布时间】:2012-10-19 03:03:05
【问题描述】:

我正在尝试编写一个 vba word 宏来搜索所有打开的文档,查找所有出现的文本“DocumentEnd9999”,并删除每个文档中该文本下方的所有内容。

Sub deletion()

Dim endTerm As String
endTerm = "DocumentEnd9999"

'Loop Dim
Dim n, c As Integer
n = Application.Documents.Count

For c = 1 To n
    Set myRange = Application.Documents(c).StoryRanges
    For Each myRange In ActiveDocument.StoryRanges
        Selection.Find.ClearFormatting
        With Selection.Find
            .Text = endTerm
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
        End With
        Selection.Find.Execute
        Selection.Extend
        Selection.Find.ClearFormatting
        With myRange.Find
            myRange.Characters.Last.Select
            .Forward = True
            .Wrap = wdFindAsk
        End With
        Application.DisplayAlerts = False
        Selection.Find.Execute
        Selection.Delete
    Next myRange
Next c

End Sub

【问题讨论】:

    标签: vba loops ms-word documents


    【解决方案1】:

    以下代码应该可以满足您在文档主体中查找的内容。不确定您使用 StoryRanges 的确切原因。我对那个集合不太熟悉,所以我没有收录它。

    Sub deletion()
    
        Dim endTerm As String
        endTerm = "DocumentEnd9999"
    
        Dim n, c As Integer
        n = Application.Documents.Count
        c = 1
    
        Dim r As Range
    
        Windows(c).Activate
    
        Selection.Find.ClearFormatting
            With Selection.Find
                .Text = endTerm
                .Forward = True
                .Wrap = wdFindContinue
            End With
    
        Do
    
            Selection.Find.Execute    
    
            Set r = ActiveDocument.Range(Selection.Range.Start, ActiveDocument.Content.End)
            r.Delete
    
            c = c + 1
    
            On Error Resume Next
            Windows(c).Activate
    
        Loop Until c > n
    
    End Sub
    

    【讨论】:

    • 完美运行。我使用storyRanges是因为我不知道我在做什么。谢谢!
    • @user1783736,太好了!很高兴它对你有效。感谢您的反馈。
    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多