Continuando con ListBox es muy padre compartirles como filtrar datos por rango de fechas de una hoja de Excel y cargarlos a un ListBox. La columna a evaluar es la columna C fecha.
Para que esto sea posible realizar lo siguiente:
- Crear una hoja con datos.
- Ingresar al editor VBA excel.
- Insertar un formulario con los componentes:
- Etiqueta (Label1).
- Caja de texto (TextBox1).
- Etiqueta (Label2).
- Caja de texto (TextBox2).
- Botón de comando (CommandButton1).
Private Sub UserForm_Initialize()
Me.TextBox1.Text = Date
Me.TextBox2.Text = Date
End Sub
Private Sub CommandButton1_Click()
Dim lngregistros, i As Long
Dim intfila As Integer
Dim dtfechini As Date
Dim dtfechfin As Date
'Definimos el número de columnas
Me.ListBox1.ColumnCount = 7
'Definimos el ancho de cada columna
Me.ListBox1.ColumnWidths = "30;160;80;80;80;80;80"
'Limpiar el lixtbox
ListBox1.Clear
'Agregar el elemento en las respectivas columnas
ListBox1.AddItem
intfila = ListBox1.ListCount - 1
ListBox1.Column(0, intfila) = "ID"
ListBox1.Column(1, intfila) = "NOMBRE"
ListBox1.Column(2, intfila) = "FEC_NAC"
ListBox1.Column(3, intfila) = "SEXO"
ListBox1.Column(4, intfila) = "DIRECCION"
ListBox1.Column(5, intfila) = "TELEFONO"
ListBox1.Column(6, intfila) = "CORREO"
'Contamos el numero de registros en la hoja 1
lngregistros = Hoja1.Range("A1").CurrentRegion.Rows.Count
'Se capturan las fechas
dtfechini = Me.TextBox1.Text
dtfechfin = Me.TextBox2.Text
'Recorre todos los registros a partir de la fila 2 de la hoja1
For i = 2 To lngregistros
'Si el valor de la columna C de cada celda sea mayor o igual a la fecha inicial
' Y el valor de la columna C de cada celda sea menor o igual a la fecha final entonces...
If Hoja1.Cells(i, 3) >= dtfechini And Hoja1.Cells(i, 3) <= dtfechfin Then
'Carga al ListBox1 los datos
ListBox1.AddItem Hoja1.Cells(i, 1)
ListBox1.List(Me.ListBox1.ListCount - 1, 1) = Hoja1.Cells(i, 2)
ListBox1.List(Me.ListBox1.ListCount - 1, 2) = Hoja1.Cells(i, 3)
ListBox1.List(Me.ListBox1.ListCount - 1, 3) = Hoja1.Cells(i, 4)
ListBox1.List(Me.ListBox1.ListCount - 1, 4) = Hoja1.Cells(i, 5)
ListBox1.List(Me.ListBox1.ListCount - 1, 5) = Hoja1.Cells(i, 6)
ListBox1.List(Me.ListBox1.ListCount - 1, 6) = Hoja1.Cells(i, 7)
End If
Next i
End Sub
Hoja 1 con datos
Filtrado de datos por rango de fechas
No hay comentarios.:
Publicar un comentario