Saltar al contenido
PROGRAMAR EN VBA MACROS DE EXCEL

Como buscar datos por cliente entre rango de fechas y cargar en listbox


.

En el presente post se muestra como buscar datos por cliente y entre un rango de fechas o fecha inicial y fecha final cargando datos a listbox; el ejemplo muestra como ingresando una fecha inicial y fecha final se pueden cargar datos que se encuentren en el rango a un listbox, adicionando que si se requiere filtrar ademas por cliente que coincidan con lo escrito en el textbox Cliente, el ejemplo lo puede hacer.

Otros post relacionados:
Como escribir en el listbox el total de registros e importes
Como cargar cabecera o header buscar datos por cliente entre rango de fechas y cargar en listbox
Como buscar datos por cliente entre un rango de fechas

Como buscar datos entre rango de fechas
Como pasar datos listbox a otro listbox con enter

Como crear una factura o sale invoice seleccionando cliente de listbox
Como crear una factura o sale invoice y grabar guardar PDF XLS y enviar por mail
Buscar en listbox mientras se escribe en textbox

Antes de seguir recomiendo leer un excelente libro sobre Excel que te ayudará operar las planillas u hojas de cálculo, haz click acá, si quieres aprender sobre Excel, en inglés, entonces debes hacer click here. Si lo que necesitas es aprender o profundizar sobre la programación de macros con VBA este es unos de los mejores cursos on line que he visto en internet.

  
Al descargar el ejemplo y presionando el botón que se encuentra en la hoja de Excel, se muestra un formulario donde existe un textbox para ingresar fecha inicial otro para fecha final y un tercer textbox para ingresar el nombre del cliente, por otra parte existe un botón de comando para ejecutar la búsqueda en un rango de fechas y cargar al listbox, el otro botón es para salir del formulario.

Como se explicó si solo se requiere filtrar entre fecha y fecha o rango de fechas solo se debe ingresar el la fecha inicial y la fecha final, luego de ello presionar el botón buscar o filtrar que en este ejemplo tiene una lupa; la macro se ejecutará mostrando en el listbox solo los datos que se encuentren dentro del rango de datos.

Si además de la fecha inicial y fecha final se quisiera filtrar por clientes, se deberá escribir el nombre del cliente en el tercer textbox, teniendo como particularidad que la macro irá buscando los datos a medida que se escribe en el textbox, es decir se buscará mientras se escribe en textbox y cargará al listbox.

El siguiente es el código que realiza la búsqueda por cliente y entre rango de fechas, si si observa que para que filtre por rango de fecha y además por el cliente se apela a una instrucción If que establece que todo dato verdadero se agregue al listbox, es decir la fila correspondiente recorrida por el bucle es igual a la cadena de caracteres escrita en clientes y que se encuentre entre el rango de fechas dadas.

For i = 2 To uf
   strg = b.Cells(i, 1).Value
   dato0 = CDate(b.Cells(i, 2).Value)
   If UCase(strg) Like UCase(TextBox1.Value) & «*» And dato0 >= dato1 And dato0 <= dato2 Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
   End If
Next i

El vídeo que sigue muestra una explicación más detallada y gráfica de la macro presentada, recomiendo observar para una más fácil comprensión de la macro; suscribe a nuestra web desde la parte superior derecha de la página ingresando tu mail y a nuestro canal de You Tube para recibir en tu correo vídeos explicativos sobre macros interesantes, como  por ejemplo Recorre fila buscando y comparando datos de dos columnas en hojas distintasbuscar en listbox mientras escribes en textbox, como crear una factura o sale invoice y grabar guardar PDF XLS y enviar por mailconectar Excel con Access y muchos ejemplos más.


if (payload.eventType == ‘subscribe’) {
// Add code to handle subscribe event.
} else if (payload.eventType == ‘unsubscribe’) {
// Add code to handle unsubscribe event.
}
if (window.console) { // for debugging only
window.console.log(‘YT event: ‘, payload);
}
}

Código que se inserta en un módulo
Private Sub CommandButton1_Click()
Unload Me
End Sub

Private Sub CommandButton2_Click()
On Error Resume Next
Set b = Sheets(«Hoja1»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
dato1 = CDate(TextBox2)
dato2 = CDate(TextBox3)
If dato2 = Empty Or dato1 = emtpy Then
MsgBox («Debe ingresar datos para consulta entre rango de fechas»), vbCritical, «AVISO»
Exit Sub
End If
If dato2 < dato1 Then
MsgBox («La fecha final no puede ser mayor a la fecha inicial»), vbCritical, «AVISO»
Exit Sub
End If

b.AutoFilterMode = False
Me.ListBox1 = Clear
Me.ListBox1.RowSource = Clear

For i = 2 To uf
   dato0 = CDate(b.Cells(i, 2).Value)
   If dato0 >= dato1 And dato0 <= dato2 Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
   End If
Next i
Me.ListBox1.ColumnWidths = «170 pt;50 pt;50 pt;50 pt;50 pt;50 pt;50 pt»
End Sub

Private Sub CommandButton3_Click()
Unload UserForm1
End Sub

Private Sub TextBox1_Change()
On Error Resume Next
Set b = Sheets(«Hoja1»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
If Trim(TextBox1.Value) = «» Then
     ‘Me.ListBox1.List() = b.Range(«A2:H» & uf).Value
     Me.ListBox1.RowSource = «Hoja1!A2:G» & uf
   Exit Sub
End If

b.AutoFilterMode = False
Me.ListBox1 = Clear
Me.ListBox1.RowSource = Clear
dato1 = CDate(TextBox2)
dato2 = CDate(TextBox3)
If dato1 <> Empty Or dato2 <> Empty Then GoTo rango:
If dato2 < dato1 Then
MsgBox («La fecha final no puede ser mayor a la fecha inicial»), vbCritical, «AVISO»
Exit Sub
End If
For i = 2 To uf
   strg = b.Cells(i, 1).Value
   If UCase(strg) Like UCase(TextBox1.Value) & «*» Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
   End If
Next i

rango:

For i = 2 To uf
   strg = b.Cells(i, 1).Value
   dato0 = CDate(b.Cells(i, 2).Value)
   If UCase(strg) Like UCase(TextBox1.Value) & «*» And dato0 >= dato1 And dato0 <= dato2 Then
       Me.ListBox1.AddItem b.Cells(i, 1)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 1) = b.Cells(i, 2)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 2) = b.Cells(i, 3)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 3) = b.Cells(i, 4)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 4) = b.Cells(i, 5)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 5) = b.Cells(i, 6)
       Me.ListBox1.List(Me.ListBox1.ListCount – 1, 6) = b.Cells(i, 7)
   End If
Next i

Me.ListBox1.ColumnWidths = «170 pt;50 pt;50 pt;50 pt;50 pt;50 pt;50 pt»
End Sub

Private Sub UserForm_Initialize()
Dim fila As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set b = Sheets(«Hoja1»)
uf = b.Range(«A» & Rows.Count).End(xlUp).Row
uc = b.Cells(1, Columns.Count).End(xlToLeft).Address
wc = Mid(uc, InStr(uc, «$») + 1, InStr(2, uc, «$») – 2)
With Me.ListBox1
    .ColumnCount = 7
    .ColumnWidths = «170 pt;50 pt;50 pt;50 pt;50 pt;50 pt;50 pt»
    .RowSource = «Hoja1!A2:» & wc & uf
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
On Error GoTo Fin
If CloseMode <> 1 Then Cancel = True
Fin:
End Sub

Si te fue de utilidad puedes INVITARME UN CAFÉ y de esta manera ayudar a seguir manteniendo la página, CLICK para descargar en ejemplo en forma gratuita.


.

If this post was helpful INVITE ME A COFFEE and so help keep up the page, CLICK to download free example.

Si te gustó por favor compártelo con tus amigos
If you liked please share it with your friends