Come utilizzare RegEx in Microsoft Word - Suggerimenti per Excel

Lissa chiede:

C'è un modo per cambiare un numero (sempre un numero casuale) dopo la parola volpe? Esempio: volpe 23, orso 1, volpe 398, rana 12, volpe 15. Voglio cambiare il numero con lo stesso colore della parola volpe.

Possiamo trovare e sostituire in base al formato in Microsoft Word. Questa è un'ottima funzionalità per trovare rapidamente il testo formattato e persino sostituire l'intero formato di testo nel documento.

Seleziona Ricerca avanzata sulla barra multifunzione.

Finestra di dialogo Trova e sostituisci

Immettere il testo da trovare, quindi fare clic sul pulsante Altro per visualizzare le opzioni avanzate e fare clic sul pulsante Formato.

Opzioni di ricerca avanzate

Seleziona l'opzione Carattere nelle impostazioni, quindi puoi impostare il colore del testo che desideri trovare nel documento. Fare clic su OK per chiudere la finestra di dialogo Trova carattere.

Seleziona il colore del testo nella finestra di dialogo Trova carattere.

Fai clic su Trova successivo e vedrai che verrà selezionata la prima occorrenza del testo cercato in un determinato colore.

Trova successivo per trovare la prima occasione.

Possiamo anche effettuare ricerche più complicate utilizzando i caratteri jolly. Tuttavia, il modulo di ricerca nativo di Word non ci consente di effettuare una ricerca come ha chiesto Lissa.

È lì che possiamo chiamare RegEx nel gioco!

Libreria di espressioni regolari VBSCript

VBA non viene fornito con alcun supporto per le espressioni regolari. Tuttavia, la libreria Microsoft VBScript contiene potenti capacità di espressione regolare. Questa libreria fa parte di Internet Explorer 5.5 e versioni successive, quindi è disponibile su tutti i computer che eseguono Windows XP, Vista, 7, 8, 8.1 o 10.

Utenti Mac

Poiché Internet Explorer non è un'applicazione per Mac, questa libreria non esiste in Mac. Pertanto, gli esempi VBA di seguito non funzionano su Mac.

Per utilizzare questa libreria in VBA, passare a VBE, selezionare Progetto e riferimenti nel menu VBE, quindi scorrere l'elenco fino a trovare l'elemento "Microsoft VBScript Regular Expressions 5.5" e spuntarlo per includerlo nell'applicazione.

Libreria di espressioni regolari VBScript

Inserisci un nuovo modulo e copia e incolla il seguente codice in questo modulo.

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

Questa procedura prende il testo di esempio, trova i codici prodotto in base al modello dato - che inizia con "volpe", spazio singolo e un numero, e stampa i codici corrispondenti nella finestra Immediata (premi Ctrl + G in VBE se non lo è visibile già).

Codici prodotto corrispondenti stampati nella finestra Immediata.

d+ La classe di caratteri nel modello definisce uno o più caratteri numerici e il modello è fondamentalmente un prefisso "volpe" seguito da uno spazio seguito da numeri.

Ulteriori informazioni

Visitare Regular Expression Language - Quick Reference per ulteriori informazioni sulle fughe di caratteri, classi di caratteri e ancore.

Copia e incolla il seguente codice per vedere RegEx in azione per rimuovere gli spazi dai codici prodotto.

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.

Replaced text printed 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.

Sample Text

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:

  1. Find the matches with RegEx.
  2. Search each matched text by using Word Find method.
  3. Find the color of the first word in the found range.
  4. 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.

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.

Sample data in Excel

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.

Result in Excel

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

Articoli interessanti...