问题
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