Macro en Word para extraer datos clave de un XML CFDI y llenar plantillas fácilmente
- Obtener vínculo
- X
- Correo electrónico
- Otras apps
En el trabajo contable o administrativo es común recibir facturas electrónicas en formato XML (CFDI). Muchas veces necesitamos extraer datos como el RFC del emisor, el RFC del receptor, el UUID o el total, y luego usarlos en un documento o correo.
📧 (Opcional) Prepararlos para enviar por correo
✅ ¿Para qué sirve esta macro?
Esta herramienta es ideal si trabajas con:
-
Declaraciones o reportes que requieren los datos de la factura.
-
Comprobación de pagos.
-
Cartas de recepción o confirmación que incluyen UUID o RFC.
-
Automatización de tareas repetitivas con múltiples CFDIs.
🧾 ¿Qué datos extrae la macro?
Desde un XML CFDI válido, obtiene:
-
✅ RFC del emisor
-
✅ RFC del receptor
-
✅ UUID del comprobante fiscal
-
✅ Monto total de la factura
🧩 Código completo de la macro en Word
Presiona Alt + F11
en Word para abrir el editor de VBA, luego inserta un nuevo módulo y pega este código:
Sub LeerMultiplesCFDIsYCrearTabla() Dim xmlDoc As Object Dim archivos As Variant Dim i As Integer Dim rfcEmisor As String, rfcReceptor As String, uuid As String, total As String Dim tabla As Table Dim fila As Integer Dim excelApp As Object ' Crear instancia de Excel para usar GetOpenFilename On Error Resume Next Set excelApp = GetObject(, "Excel.Application") If excelApp Is Nothing Then Set excelApp = CreateObject("Excel.Application") On Error GoTo 0 ' Seleccionar múltiples archivos XML archivos = excelApp.GetOpenFilename("Archivos XML (*.xml), *.xml", , "Selecciona uno o varios archivos XML", , True) If Not IsArray(archivos) Then Exit Sub ' Crear tabla en el documento actual Set tabla = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=1, NumColumns:=4) With tabla .Cell(1, 1).Range.Text = "RFC Emisor" .Cell(1, 2).Range.Text = "RFC Receptor" .Cell(1, 3).Range.Text = "UUID" .Cell(1, 4).Range.Text = "Total" .Rows(1).Range.Bold = True End With fila = 2 ' Procesar cada archivo XML For i = LBound(archivos) To UBound(archivos) Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0") xmlDoc.async = False xmlDoc.Load archivos(i) If xmlDoc.ParseError.ErrorCode = 0 Then xmlDoc.setProperty "SelectionNamespaces", _ "xmlns:cfdi='http://www.sat.gob.mx/cfd/4' xmlns:tfd='http://www.sat.gob.mx/TimbreFiscalDigital'" On Error Resume Next rfcEmisor = xmlDoc.SelectSingleNode("//cfdi:Emisor").Attributes.getNamedItem("Rfc").Text rfcReceptor = xmlDoc.SelectSingleNode("//cfdi:Receptor").Attributes.getNamedItem("Rfc").Text total = xmlDoc.SelectSingleNode("//cfdi:Comprobante").Attributes.getNamedItem("Total").Text uuid = xmlDoc.SelectSingleNode("//tfd:TimbreFiscalDigital").Attributes.getNamedItem("UUID").Text On Error GoTo 0 ' Agregar fila a la tabla tabla.Rows.Add tabla.Cell(fila, 1).Range.Text = rfcEmisor tabla.Cell(fila, 2).Range.Text = rfcReceptor tabla.Cell(fila, 3).Range.Text = uuid tabla.Cell(fila, 4).Range.Text = total fila = fila + 1 End If Next i MsgBox "Se procesaron " & (fila - 2) & " archivos XML.", vbInformation, "Macro CFDI" End SubSe debe ver así✨ ¿Cómo usar esta macro?
Abre Word y presiona
Alt + F11
para entrar al editor de macros.Crea un nuevo módulo (Insertar > Módulo) y pega el código.
Guarda el documento con macros habilitadas (
.docm
).Ejecuta la macro
LeerCFDIDesdeXML
.Selecciona tu archivo XML de factura.
Se mostrará una ventana con los datos clave extraídos.
El resultado será como se ve en la imagen🧠 Conclusión
Con esta macro puedes ahorrar tiempo y evitar errores al capturar datos de facturas XML.
Es una solución práctica y adaptable para contadores, auxiliares administrativos y cualquierprofesional que trabaje con CFDI.
Si quieres comprar la macro, te comparto la liga en mercado Libre
Si quieres cotizar una macro contáctame al correo zelideth27@gmail.com
- Obtener vínculo
- X
- Correo electrónico
- Otras apps
Comentarios
Publicar un comentario
Dejanos tus dudas y comentarios