¿Cómo crear un UserForm con búsqueda en listbox con varias hojas en combobox?

Tengo un UserForm con un combobox el cual me muestra todas las hojas del documento las cuales son muchas, que al tocar en un automáticamente te dirige a la misma, por otro lado tengo un listbox con un input el cual me filtra lo que voy escribiendo en una hoja, ¿mi consulta seria como hago para que el listbox me busque en la hoja que esta marcada en el combobox o en su defecto en la que estoy parado en el momento de buscar?

O en lugar de filtrar agregar un botón de buscar, es lo mismo supongo...

Adjunto imagen de UserForm para mayor comprensión.

Respuesta
1

Te anexo la opción para buscar presionando el botón

Private Sub CommandButton1_Click()
'Por Dante Amor
    'Buscar información en la hoja seleccionada en el combo
    '
    If ComboBox1.Value = "" Or ComboBox1.ListIndex = -1 Then
        MsgBox "Seleciona una hoja en el combo"
        ComboBox1.SetFocus
        Exit Sub
    End If
    If TextBox1.Value = "" Then
        MsgBox "Captura un dato en el textbox"
        TextBox1.SetFocus
        Exit Sub
    End If
    '
    ListBox1.Clear
    Set h = Sheets(ComboBox1.Value)
    u = h.UsedRange.Rows(h.UsedRange.Rows.Count).Row
    For i = 2 To u
        Set b = h.Rows(i).Find(TextBox1.Value, lookat:=xlPart)
        If Not b Is Nothing Then
            ListBox1.AddItem h.Cells(b.Row, "A")
            ListBox1. List(ListBox1.ListCount - 1, 1) = h. Cells(b.Row, "B")
            ListBox1. List(ListBox1.ListCount - 1, 2) = h. Cells(b.Row, "C")
            ListBox1. List(ListBox1.ListCount - 1, 3) = h. Cells(b.Row, "D")
            ListBox1. List(ListBox1.ListCount - 1, 4) = h. Cells(b.Row, "E")
            ListBox1. List(ListBox1.ListCount - 1, 5) = h. Cells(b.Row, "F")
            ListBox1. List(ListBox1.ListCount - 1, 6) = h. Cells(b.Row, "G")
            ListBox1. List(ListBox1.ListCount - 1, 7) = h. Cells(b.Row, "H")
        End If
    Next
End Sub

Hay que afinar algunos detalles, por ejemplo:

¿La búsqueda es en todas las columnas?

¿En cuál fila iniciar la búsqueda?

¿Cuáles columnas vas a poner en el listbox?

¿Y qué posición del lisbox va cada columna?


La macro que te puse, realiza la búsqueda en todas las columnas.

Tomas las primeras 8 columnas de la A a la H y en ese orden las pone en el listbox.


Buenas noches Dante, te paso el código que me enviaste con algunos agregados que tu ya debes de saber pero ta, je je

Private Sub ComboBox1_Change()
SelHoja = ComboBox1.Value
Worksheets(SelHoja).Select
End Sub
Private Sub CommandButton1_Click()
    'Buscar información en la hoja seleccionada en el combo
    If ComboBox1.Value = "" Or ComboBox1.ListIndex = -1 Then
        MsgBox "Seleciona una hoja para continuar"
        ComboBox1.SetFocus
        Exit Sub
    End If
    If TextBox1.Value = "" Then
        MsgBox "Ingrese el dato a buscar"
        TextBox1.SetFocus
        Exit Sub
    End If
    '
    ListBox1.Clear
    Set h = Sheets(ComboBox1.Value)
    u = h.UsedRange.Rows(h.UsedRange.Rows.Count).Row
    For i = 2 To u
        Set b = h.Rows(i).Find(TextBox1.Value, lookat:=xlPart)
        If Not b Is Nothing Then
            ListBox1.AddItem h.Cells(b.Row, "A")
            ListBox1.List(ListBox1.ListCount - 1, 1) = h.Cells(b.Row, "B")
            ListBox1.List(ListBox1.ListCount - 1, 2) = h.Cells(b.Row, "C")
            ListBox1.List(ListBox1.ListCount - 1, 3) = h.Cells(b.Row, "D")
            ListBox1.List(ListBox1.ListCount - 1, 4) = h.Cells(b.Row, "E")
            ListBox1.List(ListBox1.ListCount - 1, 5) = h.Cells(b.Row, "F")
            ListBox1.List(ListBox1.ListCount - 1, 6) = h.Cells(b.Row, "G")
            ListBox1.List(ListBox1.ListCount - 1, 7) = h.Cells(b.Row, "H")
       Me.TextBox2 = ComboBox1.Text
        End If
    Next
End Sub
Private Sub CommandButton2_Click()
'ESTE BOTON OCULTA PLANILLA EXCEL
    Application.Visible = False
End Sub
Private Sub CommandButton3_Click()
'ESTE BOTON MUESTRA PLANILLA EXCEL
    Application.Visible = True
End Sub
Private Sub CommandButton4_Click()
'ESTE BOTON CIERRA EL FORMULARIO
    End
End Sub
Private Sub CommandButton5_Click()
'ESTE BOTON LIMPIA LOS CAMPOS
' "ComboBox1" NO ENCONTRE LA FORMA DE LIMPIARLO
TextBox1 = Clear
TextBox2 = Clear
ListBox1.Clear
End Sub
Private Sub UserForm_Initialize()
Me.ListBox1.ColumnCount = 8
Call CargarHojas
End Sub
Sub CargarHojas()
For Each hoja In ThisWorkbook.Sheets
    ComboBox1.AddItem hoja.Name
Next
End Sub

Saber que no busca solo en las primeras 8 lineas, busca en cualquier linea y solo te devolvía la fila A, le agregue la linea "Me.ListBox1.ColumnCount= 8 " para poner ver 8 filas.

Ejemplo, tengo el dato "nombre" en el rango A1 y "precio" en el rango "AZ1" y si escribo el precio me encuentra la fila pero me muestra solo el nombre, no se si me explico bien..

¿Habrá forma de que solo busque en las primeras 8 filas y omita el resto?

Te agradezco un montón de ante mano por toda tu ayuda y el excelente código que me compartiste, me ayudo muchísimo, mil gracias dante.

En realidad no te entiendo.

Vamos a aclarar algo, en la hoja de excel, las marcadas con A, B, C, D, etc son columnas y tú las llamas filas.

Tu comentario:

"Me.ListBox1.ColumnCount= 8 " para poner ver 8 filas.

Debería ser:

"Me.ListBox1.ColumnCount= 8 " para poner ver 8 columnas.

Ahí mismo en la propiedad dice: ColumnCount, "Cantidad de Columnas"


Prueba la macro con valores de texto. Después afinamos los numéricos y los de fecha.

La macro la probé y en el listbox muestra 8 columnas.


Si tienes problemas, pon imágenes de lo que tienes en tu hoja y de lo que estás poniendo en el form.

Buenos días dante, si siempre tengo esa confusión al nombrar las columnas como filas ...

Si ingreso texto me salta enseguida pero si quiero que busque números con el formato que esta en la hoja, como pesos"$ ##.##", datos "dd/mm/yyyy" o que me muestre el contenido de celdas que están calculadas con fórmulas, ¿qué son la mayoría de mis planillas? ¿Es muy complicado de hacer o basta con agregar alguna línea?

Un saludo y agradezco tu ayuda..

Viste mi comentario:

Prueba la macro con valores de texto. Después afinamos los numéricos y los de fecha.

En el textbox, como su nombre lo dice, tienes una caja de texto, entonces aunque aparentemente capturas un número, realmente tienes un texto, lo que se debe hacer es convertir el texto a número.


Te anexo los cambios para convertir el texto a número o a fecha según sea el caso. También agregué el parámetro lookin para buscar en valores en caso de tener fórmulas.

Private Sub CommandButton1_Click()
'Por Dante Amor
    'Buscar información en la hoja seleccionada en el combo
    '
    If ComboBox1.Value = "" Or ComboBox1.ListIndex = -1 Then
        MsgBox "Seleciona una hoja en el combo"
        ComboBox1.SetFocus
        Exit Sub
    End If
    If TextBox1.Value = "" Then
        MsgBox "Captura un dato en el textbox"
        TextBox1.SetFocus
        Exit Sub
    End If
    '
    ListBox1.Clear
    dato = TextBox1.Value
    If IsDate(dato) Then
        dato = CDate(dato)
    ElseIf IsNumeric(dato) Then
        dato = CDbl(dato)
    End If
    '
    Set h = Sheets(ComboBox1.Value)
    u = h.UsedRange.Rows(h.UsedRange.Rows.Count).Row
    For i = 2 To u
        Set b = h.Rows(i).Find(dato, lookat:=xlPart, LookIn:=xlValues)
        If Not b Is Nothing Then
            ListBox1.AddItem h.Cells(b.Row, "A")
            ListBox1. List(ListBox1.ListCount - 1, 1) = h. Cells(b.Row, "B")
            ListBox1. List(ListBox1.ListCount - 1, 2) = h. Cells(b.Row, "C")
            ListBox1. List(ListBox1.ListCount - 1, 3) = h. Cells(b.Row, "D")
            ListBox1. List(ListBox1.ListCount - 1, 4) = h. Cells(b.Row, "E")
            ListBox1. List(ListBox1.ListCount - 1, 5) = h. Cells(b.Row, "F")
            ListBox1. List(ListBox1.ListCount - 1, 6) = h. Cells(b.Row, "G")
            ListBox1. List(ListBox1.ListCount - 1, 7) = h. Cells(b.Row, "H")
            Me.TextBox2 = ComboBox1.Text
        End If
    Next
End Sub

Para buscar fechas, deberás capturar algo como esto: 05/10/2018

Y en la columna de fechas deberás tener el formato de fecha dd/mm/aaaa, es decir, en la pantalla deberás ver fechas de este tipo; 05/10/2018


[No olvides valorar la respuesta.

¡Gracias! Agradezco toda tu ayuda y me disculpo por molestias ocasionadas =)

Espero poder contar con tu sabio conocimiento en cualquier otro momento,..

nunca es tarde para aprender algo nuevo .. =)

un abrazo grande a la distancia!

Atte Sebastian Torres.

La pregunta no admite más respuestas

Más respuestas relacionadas