Desafío: Sistema de Ventas y Reportes en Excel con VBA
Contexto
Una empresa de tecnología necesita simular y analizar sus ventas mensuales para entrenar a su equipo en el uso de Excel y VBA. El gerente quiere dos cosas:
Una base de datos de ventas aleatorias con formato de tabla y filtros para poder explorar la información.
Un informe resumido que muestre el total de ventas por vendedor, ordenado de mayor a menor, con formato profesional.
Prompt utilizado para poder resolver el desafio: Crea en Excel un sistema de ventas con VBA que genere automáticamente 100 registros aleatorios en una hoja llamada Ventas (con fecha, vendedor, producto, cantidad y precio unitario), convierta esos datos en una tabla con formato y filtros, y luego produzca un informe en la hoja Informe que muestre el total de ventas por vendedor ordenado de mayor a menor con estilo profesional; además, incluye un formulario con un TextBox que permita filtrar dinámicamente la tabla de ventas por nombre de vendedor.
Solución del desafío:
Código para realizar la tabla con datos aleatorios:
Option Explicit
' Genera datos aleatorios en la hoja "Ventas" con formato y filtros
Sub GenerarDatosAleatoriosConFormato()
Dim ws As Worksheet
Dim i As Long
Dim vendedores As Variant, productos As Variant
' Crear o limpiar hoja Ventas
On Error Resume Next
Set ws = ThisWorkbook.Sheets("Ventas")
If ws Is Nothing Then
Set ws = ThisWorkbook.Sheets.Add
ws.Name = "Ventas"
Else
ws.Cells.Clear
End If
On Error GoTo 0
' Dejar 4 filas en blanco y poner encabezados en fila 5
ws.Range("A5:E5").Value = Array("Fecha", "Vendedor", "Producto", "Cantidad", "Precio Unitario")
' Listas de vendedores y productos
vendedores = Array("Ana", "Luis", "Carlos", "Marta", "Sofía")
productos = Array("Laptop", "Mouse", "Teclado", "Monitor", "Impresora")
' Generar 100 filas de datos aleatorios desde la fila 6
For i = 6 To 105
ws.Cells(i, 1).Value = DateSerial(2025, Int((12 * Rnd) + 1), Int((28 * Rnd) + 1)) ' Fecha aleatoria
ws.Cells(i, 2).Value = vendedores(Int(Rnd * (UBound(vendedores) + 1))) ' Vendedor aleatorio
ws.Cells(i, 3).Value = productos(Int(Rnd * (UBound(productos) + 1))) ' Producto aleatorio
ws.Cells(i, 4).Value = Int((20 * Rnd) + 1) ' Cantidad aleatoria
ws.Cells(i, 5).Value = Round((50 + Rnd * 450), 2) ' Precio aleatorio
Next i
' Aplicar formato de tabla
Dim ultimaFila As Long
ultimaFila = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim rng As Range
Set rng = ws.Range("A5:E" & ultimaFila)
' Convertir a tabla con estilo
Dim tbl As ListObject
Set tbl = ws.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.Name = "TablaVentas"
tbl.TableStyle = "TableStyleMedium9"
' Ajustar columnas
ws.Columns("A:E").AutoFit
' Formato de columnas
ws.Columns("A").NumberFormat = "dd/mm/yyyy"
ws.Columns("D").NumberFormat = "0"
ws.Columns("E").NumberFormat = "$#,##0.00"
' Activar autofiltro automáticamente
tbl.Range.AutoFilter
End Sub
Código para generar el filtro:
Private Sub TextBox1_Change()
Dim filtro As String
filtro = "" & Me.TextBox1.Text & ""
With Sheets("Ventas").ListObjects("TablaVentas")
If Me.TextBox1.Text = "" Then
.Range.AutoFilter Field:=2 ' Mostrar todo si está vacío
Else
.Range.AutoFilter Field:=2, Criteria1:=filtro
End If
End With
End Sub
