Macros de Word VBA: buscar, buscar y reemplazar

Buscar palabra VBA

Este ejemplo es una macro de palabras simple que busca el texto "a":

Sub SimpleFind () Selection.Find.ClearFormatting con Selection.Find .Text = "a" .Replacement.Text = "" .Forward = True .Wrap = wdFindAsk .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = Falso .MatchAllWordForms = Final falso con selección.

Encontrar y reemplazar

Esta simple macro buscará la palabra "su" y la reemplazará con "allí":

Sub SimpleReplace () Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting con Selection.Find .Text = "their" .Replacement.Text = "there" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = Falso Finalizar con selección.Find.Execute Reemplazar: = wdReplaceAll End Sub

Buscar y reemplazar solo en la selección

Esta macro de VBA buscará y reemplazará texto en una selección. También pondrá en cursiva el texto reemplazado.

Sub ReplaceInSelection () 'reemplaza el texto SOLO en la selección. además, hace que el texto reemplazado esté en cursiva Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "their" With .Replacement .Font.Italic = True .Text = "there" End With .Forward = True .Wrap = wdFindStop 'esto evita que Word continúe hasta el final del documento .Format = True' también queremos reemplazar el formato del texto .MatchCase = False .MatchWholeWord = True .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End Con Selection.Find.Execute Reemplazar: = wdReplaceAll End Sub

Esta línea de código evita que VBA continúe hasta el final del documento de Word:

.Wrap = wdFindStop 'esto evita que Word continúe hasta el final del documento

Esta línea de código también indica reemplazar el formato del texto:

.Format = True 'también queremos reemplazar el formato del texto

Buscar y reemplazar solo dentro del rango

En lugar de reemplazar texto en todo el documento, o en una selección, podemos decirle a VBA que busque y reemplace solo en el rango. En este ejemplo definimos el rango como el primer párrafo:

Dim oRange As Range Establecer oRange = ActiveDocument.Paragraphs (1) .Range
Sub ReplaceInRange () 'reemplaza el texto SÓLO en el rango [en este ejemplo, solo en el primer párrafo] Dim oRange As Range Set oRange = ActiveDocument.Paragraphs (1) .Range oRange.Find.ClearFormatting oRange.Find.Replacement.ClearFormatting con oRange. Find .Text = "their" .Replacement.Text = "there" .Forward = True .Wrap = wdFindStop 'esto evita que Word continúe hasta el final del documento .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False Fin con oRange.Find.Execute Reemplazar: = wdReplaceAll End Sub 
wave wave wave wave wave