Excel a KOSMOS con un clic: envía tus pólizas desde tu hoja de cálculo (sin ser programador)
Si tu contabilidad vive en Excel, no necesitas un sistema nuevo ni un programador. Con una macro, un pequeño programa guardado dentro del propio libro, puedes revisar y enviar las pólizas del mes a KOSMOS Impuestos con un clic.
Antes de empezar
- Excel para Windows. La macro usa un componente que trae Windows; en Excel para Mac no funciona.
- Tu llave de la API (
kha_…, alcancesync), creada en el portal en Seguridad > Llaves de la API.
Paso 1. Prepara el libro
- Abre el Excel de prueba que te enviamos, o un libro tuyo con las hojas Config y Polizas.
- Ve a Archivo → Guardar como y elige Libro de Excel habilitado para macros (*.xlsm).
- Activa la pestaña Programador: Archivo → Opciones → Personalizar cinta de opciones → marca «Programador».
Paso 2. Guarda tu llave fuera del archivo
La llave nunca va dentro del Excel: si compartes el archivo, la compartirías también. Se guarda una sola vez en Windows:
- En el menú Inicio escribe variables de entorno y abre «Editar las variables de entorno de esta cuenta».
- En Variables de usuario pulsa Nueva. Nombre:
KOSMOS_API_KEY. Valor: tu llave. - Acepta y cierra y vuelve a abrir Excel.
Paso 3. Agrega la macro
- En la pestaña Programador pulsa Visual Basic.
- Archivo → Importar archivo… y elige
KOSMOS_Excel.bas, o pega el código de abajo en un módulo nuevo (Insertar → Módulo). - Cierra la ventana de Visual Basic. Listo: la macro ya vive en tu libro.
Paso 4. Llena las hojas
| Hoja | Qué va |
|---|---|
| Config | B1 = RFC, B2 = año, B3 = mes (1 a 12), B4 = razón social, B5 = régimen fiscal (601, 612…), B6 = perfil (MIN o MAX; vacío = MIN) |
| Polizas | Una fila por partida: número de póliza, fecha, tipo (I, E o D), descripción, cuenta, cargo, abono y, si la tienes, el UUID del CFDI (columna H). Las partidas de una póliza van juntas con el mismo número. |
Cada póliza debe cuadrar (cargos = abonos). Con el UUID basta: el portal completa el comprobante con el XML del CFDI. Si una póliza tiene un error, el portal rechaza solo esa y te dice cómo corregirla; las demás entran.
Paso 5. Revisa y envía
- Programador → Macros → ValidarPolizasKOSMOS → Ejecutar. El portal revisa todo sin guardar nada y te muestra el resultado.
- Si hay errores, corrige las filas que te indica y vuelve a validar.
- Cuando salga bien, ejecuta EnviarPolizasKOSMOS. Usa la API v2: abre una carga, manda las tablas y la aplica. Si reenvías el mismo mes, se reemplaza: no se duplica.
Tip: en Programador → Insertar → Botón puedes dibujar dos botones, «Validar» y «Enviar», y asignarles cada macro.
La macro completa
Es corta y está comentada. Si tienes alguien de sistemas cerca, puede revisarla en cinco minutos.
KOSMOS_Excel.bas (VBA)
Attribute VB_Name = "KOSMOS"
' KOSMOS Impuestos: enviar las pólizas de esta hoja de Excel a la API v2 (contrato 2.2.0).
' Excel para Windows (usa MSXML2.ServerXMLHTTP, incluido en Windows).
'
' Hojas que espera el libro:
' Config B1 = RFC, B2 = año, B3 = mes (1 a 12), B4 = razón social, B5 = régimen fiscal (601, 612…),
' B6 = perfil (MIN o MAX; vacío = MIN)
' Polizas fila 1 = títulos; desde la fila 2:
' A número | B fecha | C tipo (I, E o D) | D descripción | E cuenta | F cargo | G abono | H UUID del CFDI (opcional)
' Una fila por partida; las partidas de una misma póliza van juntas y con el mismo número.
' Con solo el UUID basta: el portal completa el comprobante con el XML del CFDI.
'
' La llave NO se escribe en el libro: se lee de la variable de entorno KOSMOS_API_KEY.
Option Explicit
Private Const URL_BASE As String = "https://sandbox.kosmostek.mx/api/v2"
' Revisa el mes con el portal SIN guardar nada. Úsala siempre primero.
Public Sub ValidarPolizasKOSMOS()
Dim t As Object
If Not Armar(t) Then Exit Sub
Dim doc As String
doc = "{""company"":" & t("company") & ",""policies"":[" & t("policies") & "],""lines"":[" & t("lines") & "]"
If t("documents") <> "" Then doc = doc & ",""documents"":[" & t("documents") & "]"
doc = doc & "}"
Dim r As Object
Set r = Llamar("POST", "/sync/validate?rfc=" & Texto(Hoja("Config").Range("B1").Value), doc, "")
If r Is Nothing Then Exit Sub
MsgBox "Validación (no se guardó nada) · HTTP " & r.Status & vbCrLf & vbCrLf & Left(r.responseText, 900), _
IIf(InStr(r.responseText, """valid"":true") > 0, vbInformation, vbExclamation)
End Sub
' Envía el mes al portal: abre una carga, manda cada tabla y la aplica. Reemplaza lo que había de ese mes.
Public Sub EnviarPolizasKOSMOS()
Dim cfg As Worksheet
Set cfg = Hoja("Config")
If MsgBox("¿Enviar las pólizas de " & cfg.Range("B3").Value & "/" & cfg.Range("B2").Value & _
" a KOSMOS? Se reemplaza lo que el portal tenga de ese mes.", vbYesNo + vbQuestion) <> vbYes Then Exit Sub
Dim t As Object
If Not Armar(t) Then Exit Sub
' 1. Abrir la carga
Dim r As Object, carga As String
Set r = Llamar("POST", "/sync/loads", "{""rfc"":""" & Texto(cfg.Range("B1").Value) & """,""year"":" & CLng(cfg.Range("B2").Value) & _
",""profile"":""" & Perfil() & """,""sourceSystem"":""EXCEL"",""replace"":true}", "")
If r Is Nothing Then Exit Sub
carga = Campo(r.responseText, "loadId")
If carga = "" Then
MsgBox "No se pudo abrir la carga · HTTP " & r.Status & vbCrLf & Left(r.responseText, 600), vbExclamation
Exit Sub
End If
' 2. Una parte por tabla (la misma Idempotency-Key si se repite: no se duplica)
Dim tabla As Variant
For Each tabla In Array("company", "policies", "lines", "documents")
If t(tabla) <> "" Then
Set r = Llamar("POST", "/sync/loads/" & carga & "/" & tabla, "{""rows"":[" & t(tabla) & "]}", carga & "-" & tabla)
If r Is Nothing Then Exit Sub
If r.Status >= 300 Then
MsgBox "La tabla " & tabla & " no entró · HTTP " & r.Status & vbCrLf & Left(r.responseText, 600), vbExclamation
Exit Sub
End If
End If
Next tabla
' 3. Aplicar y esperar el resultado (wait=1 sirve hasta 20,000 renglones)
Set r = Llamar("POST", "/sync/loads/" & carga & "/commit?wait=1", "{}", "")
If r Is Nothing Then Exit Sub
Dim estado As String
estado = Campo(r.responseText, "status")
If InStr(r.responseText, "V2-MES-CARGADO") > 0 Then
MsgBox "El mes ya tenía datos y no se reemplazó (V2-MES-CARGADO).", vbExclamation
Else
MsgBox "Carga " & carga & ": " & estado & " · HTTP " & r.Status & vbCrLf & vbCrLf & Left(r.responseText, 900), _
IIf(estado = "committed", vbInformation, vbExclamation)
End If
End Sub
' Arma las tablas company, policies, lines y documents (texto JSON de los renglones, separados por comas).
Private Function Armar(ByRef t As Object) As Boolean
Dim cfg As Worksheet, ws As Worksheet
Set cfg = Hoja("Config")
Set ws = Hoja("Polizas")
Set t = CreateObject("Scripting.Dictionary")
If Environ("KOSMOS_API_KEY") = "" Then
MsgBox "Falta la variable de entorno KOSMOS_API_KEY. Ver el paso 2 del instructivo.", vbExclamation
Exit Function
End If
If Texto(cfg.Range("B4").Value) = "" Or Texto(cfg.Range("B5").Value) = "" Then
MsgBox "Llena en Config la razón social (B4) y el régimen fiscal (B5).", vbExclamation
Exit Function
End If
Dim anio As Long, mes As Long
anio = CLng(cfg.Range("B2").Value): mes = CLng(cfg.Range("B3").Value)
t("company") = "{""rfc"":""" & Texto(cfg.Range("B1").Value) & """,""legalName"":""" & Texto(cfg.Range("B4").Value) & _
""",""taxRegime"":""" & Texto(cfg.Range("B5").Value) & """,""year"":""" & anio & _
""",""sourceSystem"":""EXCEL"",""profile"":""" & Perfil() & """,""schemaVersion"":""2""}"
t("policies") = "": t("lines") = "": t("documents") = ""
Dim fila As Long, ultima As Long, numero As Variant, id As String, renglon As Long
ultima = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
If ultima < 2 Then
MsgBox "La hoja Polizas no tiene renglones.", vbExclamation
Exit Function
End If
numero = Empty
For fila = 2 To ultima
If ws.Cells(fila, "A").Value <> numero Then
numero = ws.Cells(fila, "A").Value
' Identificador del contrato: tipo-año-mes-folio de 6 dígitos (I-2026-03-000001)
id = UCase(Texto(ws.Cells(fila, "C").Value)) & "-" & anio & "-" & Format(mes, "00") & "-" & Format(CLng(numero), "000000")
renglon = 0
Sumar t, "policies", "{""policyId"":""" & id & """,""date"":""" & Format(ws.Cells(fila, "B").Value, "yyyy-mm-dd") & _
""",""month"":""" & mes & """,""type"":""" & UCase(Texto(ws.Cells(fila, "C").Value)) & _
""",""description"":""" & Texto(ws.Cells(fila, "D").Value) & """,""status"":""posted""}"
End If
renglon = renglon + 1
Sumar t, "lines", "{""policyId"":""" & id & """,""line"":""" & renglon & """,""account"":""" & Texto(ws.Cells(fila, "E").Value) & _
""",""description"":""" & Texto(ws.Cells(fila, "D").Value) & """,""debit"":""" & Importe(ws.Cells(fila, "F").Value) & _
""",""credit"":""" & Importe(ws.Cells(fila, "G").Value) & """}"
If Texto(ws.Cells(fila, "H").Value) <> "" Then
Sumar t, "documents", "{""policyId"":""" & id & """,""line"":""" & renglon & """,""docType"":""CFDI"",""uuid"":""" & _
UCase(Texto(ws.Cells(fila, "H").Value)) & """}"
End If
Next fila
Armar = True
End Function
Private Sub Sumar(t As Object, tabla As String, renglon As String)
If t(tabla) <> "" Then t(tabla) = t(tabla) & ","
t(tabla) = t(tabla) & renglon
End Sub
Private Function Llamar(metodo As String, ruta As String, cuerpo As String, llaveIdem As String) As Object
Dim http As Object
Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.Open metodo, URL_BASE & ruta, False
http.setRequestHeader "Authorization", "Bearer " & Environ("KOSMOS_API_KEY")
http.setRequestHeader "Content-Type", "application/json; charset=utf-8"
http.setRequestHeader "X-Kosmos-Source", "excel-macro/2.0"
If llaveIdem <> "" Then http.setRequestHeader "Idempotency-Key", llaveIdem
http.send Utf8(cuerpo)
If http.Status = 401 Or http.Status = 402 Or http.Status = 403 Then
MsgBox "KOSMOS respondió " & http.Status & ": revisa tu llave (alcance sync) y que el despacho tenga API-SYNC." & _
vbCrLf & Left(http.responseText, 400), vbExclamation
Exit Function
End If
Set Llamar = http
End Function
' Valor de texto de un campo en la respuesta JSON ("loadId":"…").
Private Function Campo(json As String, nombre As String) As String
Dim i As Long, j As Long
i = InStr(json, """" & nombre & """:""")
If i = 0 Then Exit Function
i = i + Len(nombre) + 4
j = InStr(i, json, """")
If j > i Then Campo = Mid(json, i, j - i)
End Function
Private Function Perfil() As String
Perfil = UCase(Texto(Hoja("Config").Range("B6").Value))
If Perfil <> "MAX" Then Perfil = "MIN"
End Function
' Importe con punto decimal y 2 decimales, sin importar la configuración regional de Windows.
Private Function Importe(v As Variant) As String
If Trim(CStr(v)) = "" Then v = 0
Importe = Replace(Format(CDbl(v), "0.00"), ",", ".")
End Function
' Texto seguro para JSON: escapa diagonales invertidas y comillas.
Private Function Texto(v As Variant) As String
Texto = Replace(Replace(Trim(CStr(v)), "\", "\\"), """", "\""")
End Function
' Convierte el texto a bytes UTF-8 (acentos y eñes llegan bien al portal).
Private Function Utf8(s As String) As Variant
Dim st As Object
Set st = CreateObject("ADODB.Stream")
st.Type = 2: st.Charset = "utf-8": st.Open
st.WriteText s
st.Position = 0: st.Type = 1: st.Position = 3 ' salta la marca BOM de 3 bytes
Utf8 = st.Read
st.Close
End Function
Private Function Hoja(nombre As String) As Worksheet
Set Hoja = ThisWorkbook.Worksheets(nombre)
End Function
¿Quieres el Excel de prueba o una demostración? silvano@kosmostek.net · +52 55 1397 5173.
¿Programas en otro lenguaje? Tenemos ejemplos en 21 lenguajes.
