I am new to VBA programming and I have a problem. I am trying to automatice words documents. I have a template document with generic names and I need to use a VBA code in excel to replace those generic names with concrete names. The problem is when I use the .Find function either way it does not work. I made a simple example in which I printed on the debug screen a couple of lines that does not use the mentioned function but when I use it, it does not print. That is to say the result of the following code is this:
Texto a buscar: NOMBRE
Reemplazo: hello
Thank you
Sub Prueba2()
Dim WordApp As Object 'Aplicación Word
Dim PlantillaDoc As Object 'Word plantilla
' Inicializar la aplicación de Word
On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If WordApp Is Nothing Then
Set WordApp = CreateObject("Word.Application")
End If
WordApp.Visible = True 'Solo para depurar
Set PlantillaDoc = WordApp.Documents.Open("C:UsersalsanchezDocumentsAutomatización de ProyectosadsgasdfgNuevo Documento de Microsoft Word.docx")
' Configuración de búsqueda
Dim TextoBuscado As String
Dim ReemplazoTexto As String
TextoBuscado = "NOMBRE"
ReemplazoTexto = "hello"
Debug.Print "Texto a buscar: " & TextoBuscado
Debug.Print "Reemplazo: " & ReemplazoTexto
Debug.Print "Dirección de búsqueda: " & IIf(PlantillaDoc.Find.Forward, "Hacia adelante", "Hacia atrás")
Debug.Print "Envolver búsqueda: " & IIf(PlantillaDoc.Find.Wrap = wdFindContinue, "Sí", "No")
Debug.Print "Coincidir mayúsculas/minúsculas: " & IIf(PlantillaDoc.Find.MatchCase, "Sí", "No")
'Reemplazo del texto de la plantilla por nombres concretos
PlantillaDoc.Content.Find.ClearFormatting
PlantillaDoc.Content.Find.Replacement.ClearFormatting
With PlantillaDoc.Content.Find
.Text = TextoBuscado
.Replacement.Text = ReemplazoTexto
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
' Ejecutar búsqueda y reemplazo
PlantillaDoc.Content.Find.Execute Replace:=2
End Sub
Álvaro Sánchez Gómez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.