VBA Word - Finding specific text in a document and replacing the content of the paragraph following that specific text

痴心易碎 提交于 2021-02-11 12:18:08

问题


Here is a sample of text from my word document : https://www.noelshack.com/2018-31-2-1533054408-word.png

I am new to VBA and I am trying to write a macro that looks for the specific text """"Eligible Currency"" means the Base Currency and each other currency specified here:" and replace the two following lines (filled with some dots, not necessarily in the same paragraph) with a list of text (for instance : Euro, Dollar).

So far I have been able to loop through the document, find the specific text and edit it, using the code :

Sub FindAndFormat()
    Dim objWord As Object
    Dim wdDoc As Object
    Dim ParagraphRange As Object
    Dim intParaCount
    On Error Resume Next
    Set objWord = GetObject(, "Word.Application")
    If Err.Number <> 0 Then
        Set objWord = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set wdDoc = objWord.Documents.Open("D:\Modele.docx")
    objWord.Visible = True
    Dim Paragraph As Word.Paragraph
    For Each Paragraph In wdDoc.Paragraphs
        Set ParagraphRange = Paragraph.Range
        ParagraphRange.Find.Text = """Eligible Currency"" means the Base Currency and each other currency specified here:"
        ParagraphRange.Find.Execute
        If ParagraphRange.Find.Found Then
            ParagraphRange.Text = """Eligible Currency"" means the Base Currency and each other currency specified here: Euro, Dollar"
        End If
    Next
End Sub

Note that the style of the whole line is getting bold and italic.

https://www.noelshack.com/2018-31-2-1533055581-word2.png

What I really would like to achieve is replacing the dotty lines :

https://www.noelshack.com/2018-31-2-1533055647-word3.png

Now there may be several other dotty lines in my document, and they may not always contain exactly the same amount of dots.

Thank you for reading.


回答1:


Try something along the lines of:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = """Eligible Currency""[!:]@:[ ….^13^l^t]{2,}"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
    .Execute
  End With
  Do While .Find.Found
    .End = .End - 1
    .Start = .Start + InStr(.Text, ":")
    .Text = Chr(11) & vbTab
    .Collapse wdCollapseEnd
    .Text = "Euro, Dollar"
    .Font.Bold = True
    .Font.Italic = True
    .Collapse wdCollapseEnd
    .Find.Execute
  Loop
End With
Application.ScreenUpdating = True
End Sub


来源:https://stackoverflow.com/questions/51618418/vba-word-finding-specific-text-in-a-document-and-replacing-the-content-of-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!