No sumar en textbox, si no encuentra datos en listbox

Tengo 2 consultas para el mismo archivo. Tengo un listbox que se llena mediante un rango de fechas, y un textbox suma los valores de una columna. El problema es que cuando no encuentra una fecha dentro del rango, me manda un error porque el textbox no encuentra nada en la columna del listbox.

Y el otro tema es saber como puedo usar los mismos criterios en el autofiltro, pero que busque en dos field. Me explico, tengo una columna con un rango de fechas (U2) y otra columna (V2), yo quiero saber si al buscar fecha inicio y fecha fin pueda buscar dentro de estos dos rangos, manteniendo los mismos criterios.

2 respuestas

Respuesta
1

Cristian, buen dia!

Te paso la macro para realizar los filtros.

Sub FilterDate()
'Written by Juan Manuel Cosceri

Dim StartDate As Date
Dim EndDate As Date

StartDate = Range("a1").Value 'Replace por TextBoxTo
EndDate = Range("b1").Value 'Replace por TextBoxFrom
Set Sh1 = Sheets("Hoja1")
LastRow = Sh1.Range("A1048576").End(xlUp).Row

Sh1.Activate

LastRow = Sh1.Range("A1048576").End(xlUp).Row
Sh1.Range(Cells(2, 1), Cells(LastRow, 24)).AutoFilter Field:=21, Criteria1:=">=" & StartDate, Operator:=xlAnd
Sh1.Range(Cells(2, 1), Cells(LastRow, 24)).AutoFilter Field:=22, Criteria1:="<=" & EndDate, Operator:=xlAnd
Sh1. Range(Cells(2, 1), Cells(LastRow, 24)). SpecialCells(xlCellTypeVisible).Select
Selection. Copy 'Copia el valor de las celdas no filtradas

*****************************************************************************************

Respecto al valor deferias definir que valor deberia tomar en caso de que este vacio y podes gestionarlo con un IF
IF EndDate is empty OR EndDate is null OR EndDate = 0 THEN EndDate = Date

Estimado, este es el código que tengo:

Private Sub CommandButton3_Click()
Application.ScreenUpdating = False
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
If Me.TextBox48.Value = "" Then
MsgBox "Ingrese fecha de Inicio", vbInformation, "Información"
Else
If Me.TextBox77.Value = "" Then
MsgBox "Ingrese fecha de Fin", vbInformation, "Información"
Exit Sub
End If
Sheets("BIENESTAR").Select
Me.ListBox2.Clear
fecha1 = CDate(TextBox48)
fecha2 = CDate(TextBox77)
fecha1 = Format(fecha1, "mm/dd/yyyy")
fecha2 = Format(fecha2, "mm/dd/yyyy")
Range("a1").AutoFilter Field:=20, Criteria1:=">=" & fecha1, Operator:=xlAnd, Criteria2:="<=" & fecha2
For Each celda In Range("a2:a" & Range("a65000").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
Range("a2").Sort Key1:=Range("T2"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
ListBox2.AddItem celda
i = ListBox2.ListCount - 1
ListBox2.List(i, 0) = celda.Offset(0, 9)
ListBox2.List(i, 1) = celda.Offset(0, 11)
ListBox2.List(i, 2) = Format(celda.Offset(0, 18), "$#,###,###")
ListBox2.List(i, 3) = celda.Offset(0, 19)
total = 0
For i = 0 To ListBox2.ListCount - 1
total = total + CDbl(Me.ListBox2.List(i, 2))
Next i
TextBox76.Text = total
TextBox76.Value = VBA.Format(TextBox76.Value, "$#,###,###")
Next
End If
End Sub

los textbox 48 y 77 están bajo el DATEPICKER

Muchas gracias

Cristian, Buen día!

El tema es que estas usando For Each celda In Range("a2:a" & Range("a65000").End(xlUp).Row).SpecialCells(xlCellTypeVisible)

Es decir, por cada celda y tira error por que el total en ese caso en "0"

Podrias realizar el siguiente IF previo al For Each

LR = Sheets("BIENESTAR").Cells(Sheets("BIENESTAR").Rows.Count, 20).End(xlUp).Row

If LR = 1 Then 'Si el LR= es 1 no hay ningun valor que corresponda

Else 'Que llene como viene realizando normalmente

Quedaria algo asi si no me equivoco

Private Sub CommandButton3_Click()
Application.ScreenUpdating = False
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
If Me.TextBox48.Value = "" Then
MsgBox "Ingrese fecha de Inicio", vbInformation, "Información"
Else
If Me.TextBox77.Value = "" Then
MsgBox "Ingrese fecha de Fin", vbInformation, "Información"
Exit Sub
End If

Sheets("BIENESTAR").Select
Me.ListBox2.Clear
fecha1 = CDate(TextBox48)
fecha2 = CDate(TextBox77)
fecha1 = Format(fecha1, "mm/dd/yyyy")
fecha2 = Format(fecha2, "mm/dd/yyyy")
Range("a1").AutoFilter Field:=20, Criteria1:=">=" & fecha1, Operator:=xlAnd, Criteria2:="<=" & fecha2

LR = Sheets("BIENESTAR").Cells(Sheets("BIENESTAR").Rows.Count, 20).End(xlUp).Row

If LR = 1 Then

Else

For Each celda In Range("a2:a" & Range("a65000").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
Range("a2").Sort Key1:=Range("T2"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
ListBox2.AddItem celda
i = ListBox2.ListCount - 1
ListBox2.List(i, 0) = celda.Offset(0, 9)
ListBox2.List(i, 1) = celda.Offset(0, 11)
ListBox2.List(i, 2) = Format(celda.Offset(0, 18), "$#,###,###")
ListBox2.List(i, 3) = celda.Offset(0, 19)
Total = 0
For i = 0 To ListBox2.ListCount - 1
Total = Total + CDbl(Me.ListBox2.List(i, 2))
Next i
TextBox76.Text = Total
TextBox76.Value = VBA.Format(TextBox76.Value, "$#,###,###")
Next
End If
End If

End Sub

PERFECTO..!!!, FUNCIONÓ MUY BIEN.

Con respecto a los dos campos en el autofiltro, cómo podría hacerlo en ese caso?

Mm con eso lo que estas haciendo es que si no tiene FCs no entre en el bucle.

El filtro de fecha lo estas haciendo acá:

fecha1 = CDate(TextBox48)
fecha2 = CDate(TextBox77)
fecha1 = Format(fecha1, "mm/dd/yyyy")
fecha2 = Format(fecha2, "mm/dd/yyyy")

Range("a1").AutoFilter Field:=20, Criteria1:=">=" & fecha1, Operator:=xlAnd, Criteria2:="<=" & fecha2

Ahí estarías filtrando la columna "T" si no me equivoco. Según tu descripción inicial deberías filtrar las columnas "U" o "V" cambiar el Field por 21 o 22

Si el formato de Fecha que tienes es Día-Mes-Año cambia el format por "dd/mm/yyyy" o "dd/mm/aaaa" creo que es la primera opción pero a veces dependiendo de la versión de Excel varia.

Fíjate si eso te funciona y sino cualquier cosa lo vemos.

Por favor no te olvides de evaluar la respuesta!

Slds

Juan

Juan, te adjunto un screenshot de la hoja de excel para que veas las dos columnas que necesito filtrar. En realidad necesito que la macro pueda buscar fechas de inicio y fin en eso dos rangos.

Quiero llegar a buscar desde el 01/07/2017 hasta el 03/09/2017 que es la ultima fecha de la columna V.

Cristian, Buen día!

Según tengo entendido no se puede filtrar por ambas columnas ya que siempre aplica un filtro antes que el otro. la solucion que se me ocurre es que uses una columna aparte para el filtro y coloques una logica si Tn = FPago1 or T2n = FPago = then "X".

Después filtras por esa columna y listo.

Te mando el Bucle para la generación del Filtro.

**********************************************************************************************

Lastrow = Sheets("BIENESTAR").Cells(Sheets("BIENESTAR").Rows.Count, 20).End(xlUp).Row
n = 2
Do Until n > Lastrow
FechaFC1 = Format(Sheets("BIENESTAR").Range("T" & n).Value, "dd/mm/yyyy")
FechaFC2 = Format(Sheets("BIENESTAR").Range("V" & n).Value, "dd/mm/yyyy")
If FechaFC1 >= fecha1 And FechaFC1 <= fecha2 Then
Sheets("BIENESTAR").Range("W" & n).Value = "X"
ElseIf FechaFC2 >= fecha1 And FechaFC2 <= fecha2 Then
Sheets("BIENESTAR").Range("W" & n).Value = "X"
Else
Sheets("BIENESTAR").Range("W" & n).Value = ""
End If
n = n + 1
Loop

**********************************************************************************************
Fíjate de Reemplazar W por Last Column para que te lo agregue al final Ej "AA" y modifica el field del filtro por Field 27 y el campo por "X"

Range("a1").AutoFilter Field:=27, Criteria1:="x"  Operator:=xlAnd, Criteria2:="X"

Cualquier cosa Chifla.

Por favor no te olvides de valorar la respuesta!

Slds

Juan

¡Gracias! pero igualmente no me serviría Juan por que cada fecha de pago en estas dos columnas está ligado a una orden de compra y factura. Así que voy a tener que ver como lo puedo ordenar para dejar solo un rango de fechas.

Te pasaste igual, muchas gracias 

Respuesta
1

No se mucho de excel

Pero prueba la función Nz(cuadrodetexto, 0)

Funciona así: Escribe cuadro de texto, en caso que sea null pongo 0

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas