Lissa demande:
Existe-t-il un moyen de changer un nombre (toujours un nombre aléatoire) après le mot renard? Exemple: renard 23, ours 1, renard 398, grenouille 12, renard 15. Je veux changer le nombre de la même couleur que le mot renard.
Nous pouvons rechercher et remplacer par format dans Microsoft Word. C'est une fonctionnalité intéressante pour trouver rapidement le texte formaté et même remplacer le format de texte entier dans le document.
Sélectionnez Recherche avancée sur le ruban.

Entrez le texte à rechercher, puis cliquez sur le bouton Plus pour voir les options avancées, et cliquez sur le bouton Format.

Sélectionnez l'option Police dans les paramètres, puis vous pouvez configurer la couleur du texte que vous souhaitez trouver dans le document. Cliquez sur OK pour fermer la boîte de dialogue Rechercher une police.

Cliquez sur Suivant et vous verrez que la première occurrence du texte recherché dans une certaine couleur sera sélectionnée.

Nous pouvons également effectuer des recherches plus compliquées en utilisant des caractères génériques. Cependant, le module de recherche natif de Word ne nous permet pas de faire une recherche comme Lissa l'a demandé.
C'est là que nous pouvons appeler RegEx dans le jeu!
Bibliothèque d'expressions régulières VBSCript
VBA n'est livré avec aucune prise en charge des expressions régulières. Cependant, la bibliothèque Microsoft VBScript contient de puissantes capacités d'expression régulière. Cette bibliothèque fait partie d'Internet Explorer 5.5 et versions ultérieures, elle est donc disponible sur tous les ordinateurs exécutant Windows XP, Vista, 7, 8, 8.1 ou 10.
Utilisateurs Mac
Étant donné qu'Internet Explorer n'est pas une application Mac, cette bibliothèque n'existe pas sous Mac. Par conséquent, les exemples VBA ci-dessous ne fonctionnent pas sous Mac.
Pour utiliser cette bibliothèque dans VBA, basculez vers VBE, sélectionnez Projet et références dans le menu VBE, puis faites défiler la liste pour trouver l'élément «Microsoft VBScript Regular Expressions 5.5» et cochez-le pour l'inclure dans l'application.

Insérez un nouveau module et copiez et collez le code suivant dans ce module.
Sub doRegexFind() Dim strSample As String Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match strSample = "First product code is fox 12, second one is fox 22, and third product is fox 45." Set objRegex = New RegExp With objRegex .Pattern = "fox d+" .Global = True .IgnoreCase = True Set matches = .Execute(strSample) For Each fnd In matches Debug.Print fnd Next fnd End With End Sub
Cette procédure prend l'exemple de texte, trouve les codes produit par le modèle donné - qui commence par «renard», un seul espace et un nombre, et imprime les codes correspondants dans la fenêtre Exécution (appuyez sur Ctrl + G dans VBE si ce n'est pas le cas visible déjà).

d+
la classe de caractères dans le modèle définit un ou plusieurs caractères numériques, et le modèle est essentiellement le préfixe «renard» suivi d'un espace suivi de nombres.
Plus d'informations
Consultez Langage d'expression régulière - Référence rapide pour plus d'informations sur les échappements de caractères, les classes de caractères et les ancres.
Copiez et collez le code suivant pour voir RegEx en action pour supprimer les espaces des codes produit.
Sub doRegexFindReplace() Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match Dim strSample As String strSample = "First product code is fox 12, second one is fox 22, and third product is fox 45." Set objRegex = New RegExp With objRegex .Pattern = "(fox) (d+)" .Global = True .IgnoreCase = True strSample = .Replace(strSample, "$1$2") End With Debug.Print strSample End Sub
This procedure replaces the sample text content by removing the spaces from the product codes matched with the given pattern, and prints the result text in the Immediate window.

Please note that pattern is slightly different than the first code. Terms in this pattern are enclosed with parentheses, and corresponding terms are used in the Replace method as $1 and $2 in order. This procedure simply joins the two terms without spaces.
Back to the Question
Let's go back to the sample text we used at the beginning of this article.

We need to find "fox" followed by numeric characters, and change the match by using the color of the "fox" section in the matched text.
Although RegEx is very good matching by the given pattern, it cannot replace the color of text in Word document. So we will combine RegEx and Word VBA methods in the following procedure.
Here are the steps:
- Find the matches with RegEx.
- Search each matched text by using Word Find method.
- Find the color of the first word in the found range.
- Change the color of the found range with the color in the previous step.
Switch to VBE, and insert a new module. Make sure VBScript Regular Expressions library is added to the project, and copy and paste the following code into this new module.
Sub doRegexMagic() Dim str As String Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match Set objRegex = New RegExp str = "fox" With Selection .HomeKey wdStory .WholeStory End With With objRegex .Pattern = str & " d+" .Global = True .IgnoreCase = True Set matches = .Execute(Selection.Text) End With With Selection .HomeKey wdStory With .Find .ClearFormatting .Forward = True .Format = False .MatchCase = True For Each fnd In matches .Text = fnd .Execute With Selection .Font.Fill.ForeColor = .Range.Words(1).Font.TextColor .MoveRight wdCharacter End With Next fnd End With .HomeKey wdStory End With End Sub
Run the code, and here is the result.

Download Word File
To download the Word file: how-to-use-regex-in-microsoft-word.docm
RegEx in Excel?
Regex is completely missing from Excel. However, we can still use VBScript Regular Expressions in Excel VBA.
Launch Excel, open a new workbook, and create the content as shown below.

Reference
This article has been inspired by Learn Excel 2010 - "Find & Replace Color of A Certain Word": Podcast #1714 published by Bill Jelen on May 21, 2013! So we wanted to use similar sample text as he used in the video. We just added numbers after the "fox".
Switch to VBE, and insert a new module. Make sure VBScript Regular Expressions library is added to the project just like you did in Word, and copy and paste the following code into this new module.
Sub doRegexMagicInExcel() Dim str As String Dim objRegex As RegExp Dim matches As MatchCollection Dim fnd As Match Dim rng As Range Dim cll As Range Set objRegex = New RegExp Set rng = Selection str = "fox" With objRegex .Pattern = "(" & str & ") (d+)" .Global = True .IgnoreCase = True For Each cll In rng.Cells Set matches = .Execute(cll.Value) For Each fnd In matches cll.Value = .Replace(cll.Value, "$1$2") Next fnd Next cll End With End Sub
Return to worksheet, and select the range with sample text. Run the macro, and see the result.

This procedure loops through the cells in the selected range, replaces the text in the cells by removing the spaces from the product codes matched with the given RegEx pattern.
Download Excel File
To download the Excel file: how-to-use-regex-in-microsoft-excel.xlsm