#1
|
|||
|
|||
Find and replace text in a document with wildcards in vba
Salut ŕ toute la communauté
To find generic words in a word document and surround them with square brackets I use the following macro and it works: Code:
Sub test() Dim rngDoc As Word.Range Dim sArray As Variant, tArray As Variant Dim i As Long sArray = Array("ABCD.0001/0002/0003") tArray = Array("ABCD.0001", "ABCD.0002", "ABCD.0003") Set rngDoc = ActiveDocument.Range For i = 0 To UBound(sArray) With rngDoc.Find .ClearFormatting .Text = sArray(i) .Replacement.Text = "ABCD.0001 ABCD.0002 ABCD.0003" .Execute Replace:=wdReplaceAll End With Next For i = 0 To UBound(tArray) With rngDoc.Find .ClearFormatting .Text = tArray(i) .Replacement.Text = "[" & tArray(i) & "]" .Execute Replace:=wdReplaceAll End With Next End Sub Thank you |
#2
|
||||
|
||||
Perhaps:
Code:
Sub Demo() Application.ScreenUpdating = False Dim StrFnd As String, StrRep As String, i As Long, j As Long, k As Long StrFnd = "([A-Z]{4}.)([0-9]{4})|([0-9]{4})|([0-9]{4})|([0-9]{4})|([0-9]{4})" StrRep = "\1\2 \1\3 \1\4 \1\5 \1\6" j = Len(Split(StrFnd, "|")(1)) + 1: k = Len(Split(StrRep, " ")(0)) + 1 With ActiveDocument.Range With .Find .ClearFormatting .Replacement.ClearFormatting .Format = False .Forward = True .Wrap = wdFindContinue .MatchWildcards = True For i = UBound(Split(StrFnd, "|")) To 1 Step -1 .Text = StrFnd .Replacement.Text = StrRep .Execute Do While .Found = True .Execute Replace:=wdReplaceAll Loop StrFnd = Left(StrFnd, Len(StrFnd) - j): StrRep = Left(StrRep, Len(StrRep) - k) Next .Text = "[A-Z]{4}.[0-9]{4}" .Replacement.Text = "[^&]" .Execute Replace:=wdReplaceAll End With End With Application.ScreenUpdating = True End Sub
__________________
Cheers, Paul Edstein [Fmr MS MVP - Word] Last edited by macropod; 06-22-2022 at 05:23 AM. Reason: Code revision for greater efficiency |
#3
|
|||
|
|||
Hello,
Your macro works thank you very much |
|
Similar Threads | ||||
Thread | Thread Starter | Forum | Replies | Last Post |
Help with WildCards Find & Replace either or nothing... | Cendrinne | Word VBA | 9 | 11-14-2020 08:25 AM |
Advanced Find and Replace with Wildcards help needed | Amapola188 | Word | 3 | 07-23-2019 10:54 PM |
Find and replace text with wildcards | arunchandar9 | Word VBA | 15 | 06-30-2019 01:06 AM |
Using wildcards how do I Find and Add to, not replace | Stargehzer | Word | 3 | 01-25-2016 09:14 PM |
Find & Replace: Wildcards (except this pattern) | tinfanide | Word | 6 | 01-26-2014 06:39 AM |