Hacer un buscador factura-boleta

Tengo 2 bases de datos (hojas), 1era con datos de boletas en inventario con fecha, monto, etc y 2da con datos de facturas con boletas asociadas a ellas (con fecha, monto total, etc, adjunto una imagen de esta hoja). Necesito hacer un buscador que me permita ingresar un numero de factura y busque en la hoja 1 si las boletas que están asociadas a la factura en la hoja 2 están en inventario. Si no las encuentra que muestre cuales no están (ya que en la hoja 2 estarían las boletas que debieran estar en inventario) además de esto, necesito que muestre el total del monto de la factura con las boletas encontradas.

Desde ya, muy agradecido por su ayuda!

2 Respuestas

Respuesta
2

¿

¿Corrígeme si me equivoco buscas algo así?, si es así solo crea un formulario como el de la pantalla y pega el código que anexo

Private Sub ComboBox1_Change()
Dim X As WorksheetFunction
Set X = WorksheetFunction
Set BOLETAS = Range("boletas")
Set FACTURAS = Range("facturas")
factura = ComboBox1.Value
With FACTURAS
    CUENTA = X.CountIf(.Columns(1), factura)
    fila = X.Match(Val(factura), .Columns(1), 0)
    Set DESGLOSE = .Cells(fila, 2).Resize(CUENTA, .Columns.Count - 1)
    DESGLOSE.Select
    matriz = DESGLOSE
    With ListBox1
        .ColumnCount = DESGLOSE.Columns.Count
        .List = matriz
        Label6 = DESGLOSE.Rows.Count
        Label7 = X.Sum(DESGLOSE.Columns(3))
    End With
End With
Set FACTURAS = Nothing: Set BOLETAS = Nothing
End Sub
Private Sub ListBox1_Click()
Dim X As WorksheetFunction
Set X = WorksheetFunction
Set BOLETAS = Range("BOLETAS")
boleta = ListBox1.Value
CUENTA = X.CountIf(BOLETAS.Columns(1), boleta)
VALIDA = CUENTA = 0
VALIDA2 = CUENTA > 0
If VALIDA Then MsgBox ("LA BOLETA " & boleta & " NO EXISTE"), vbCritical, "AVISO EXCEL"
If VALIDA2 Then MsgBox ("LA BOLETA " & boleta & "  EXISTE"), vbExclamation, "AVISO EXCEL"
Set datos = Nothing
End Sub
Private Sub UserForm_Initialize()
Set h1 = Worksheets("hoja1")
Set h2 = Worksheets("hoja2")
Set BOLETAS = h1.Range("a1").CurrentRegion
Set FACTURAS = h2.Range("a1").CurrentRegion
With BOLETAS
    .Sort key1:=h1.Range(.Columns(1).Address), _
    order1:=xlAscending, Header:=xlYes
    .Name = "boletas"
End With
With FACTURAS
    r = .Rows.Count: c = .Columns.Count
    .Sort key1:=h2.Range(.Columns(1).Address), _
    order1:=xlAscending, Header:=xlYes
    .Name = "facturas"
    Set unicos = .Columns(c + 3).Resize(r, 1)
    With unicos
        FACTURAS.Columns(1).Copy: unicos.PasteSpecial
        .RemoveDuplicates Columns:=1
        Set unicos = .CurrentRegion
        matriz = .Rows(2).Resize(.Rows.Count - 1)
        With ComboBox1
            .Clear
            .List = matriz
        End With
        unicos.Clear
    End With
End With
set facturas=nothing: set boletas=nothing
End Sub

¡Gracias! si, algo así buscaba, le haré unas adaptaciones y quedará ok. Muchas gracias!

Te vuelvo agradecer por tu ayuda, sin embargo necesito hace unos ajustes y exceden mis conocimientos, no se si puedes ayudarme.

Me gustaría adaptarlo con el userform que adjunto a continuación:

Necesito ingresar el numero de factura dar click a buscar y que aparezcan los datos en el ListBox, que indique si alguna de las boletas asociada a la factura se encuentra en inventario (la hoja "Boletas"), abajo el monto total de las boletas asociadas a la factura (sin importar si falta alguna) y el monto total de la factura. La base de datos de facturas tiene un inconveniente, el que te muestro a continuación en la siguiente imagen:

La factura 1 se repite en la base de datos, con el mismo monto, solo va cambiando la boleta. Esto debido al método de ingreso utilizado programado de esa forma, el cual no puedo cambiar ya que hay muchísimos datos ingresados (la datos de la base de datos real no son los de la imagen, solo es un bosquejo). Necesito que el userform me muestre el monto de la factura, que puede ser cualquiera mientras pertenezca a la factura citada (ya que por el programa de ingreso el total de la factura se va repitiendo, debido a que solo van variando als boletas) para compararlo con el monto total de las boletas y así confirmar que monto cobrado en la factura concuerde con los datos en el inventario. En resumen es un programa para confirmar si el cobro de la factura es correcto o no, a pesar de que puedan faltar boletas, al menos el programa estaría dando una idea aproximada.

No se si estoy siendo claro con mi problema, si necesitas saber más dime para explicarlo mejor, te lo agradecería un montón.

¿Qué tendría que cambiar o agregar en el código?

Muchas muchas muchísimas gracias!

Es más efectivo usar un combobox en lugar de un textbox así no habría errores que den como resultado un mensaje como "esta factura no se encuentra" siguiendo con tu pantalla este es el resultado

La tabla de las boletas tiene que tener esta estructura para que funcione la macro sin problemas

y este es el codigo

Option Base 1
Private Sub CommandButton1_Click()
LLENO = TextBox1.Text <> Empty
If LLENO Then BUSCA_FACTURA
End Sub
Private Sub TextBox1_AfterUpdate()
BUSCA_FACTURA
End Sub
Private Sub UserForm_Initialize()
Dim X As WorksheetFunction
Set X = WorksheetFunction
Set H1 = Worksheets("FACTURAS")
Set H2 = Worksheets("BOLETAS")
Set FACTURAS = H1.Range("A1").CurrentRegion
Set BOLETAS = H2.Range("A1").CurrentRegion
With UserForm2
    .Move 150, 12
    .Caption = "BUSCADOR DE BOLETAS"
End With
With FACTURAS
    .Sort KEY1:=H1.Range(.Columns(1).Address), ORDER1:=xlAscending, _
    KEY2:=H1.Range(.Columns(3).Address), ORDER1:=xlAscending, _
    Header:=xlYes
    Set FACTURAS = .Rows(2).Resize(.Rows.Count - 1, .Columns.Count)
    .Name = "FACTURAS"
End With
With BOLETAS
    .Sort KEY1:=H2.Range(.Columns(1).Address), ORDER1:=xlAscending, _
    Header:=xlYes
    .Name = "BOLETAS"
End With
Set FACTURAS = Nothing: Set BOLETAS = Nothing
End Sub
Sub BUSCA_FACTURA()
    Dim X As WorksheetFunction
    Set X = WorksheetFunction
    Set FACTURAS = Range("FACTURAS")
    Set BOLETAS = Range("BOLETAS")
    FACTURA = Val(TextBox1.Text)
    LLENO = FACTURA <> Empty
    If LLENO Then
    With FACTURAS
        CUENTA = X.CountIf(.Columns(1), FACTURA)
        On Error Resume Next
        FILA = X.Match(FACTURA, .Columns(1), 0)
        XERR = Err.Number > 0
        If XERR Then
            MsgBox ("NO EXISTE ESA FACTURA"), vbCritical, "AVISO EXCEL"
            GoTo SAL
        End If
        On Error GoTo 0
        Set NFACTURA = .Rows(FILA).Resize(CUENTA)
        TextBox2.Text = Format(X.Sum(NFACTURA.Columns(4)), "$ 0,0.00")
        With NFACTURA
            R = .Columns.Count: C = .Columns.Count - 1
            Set NFACTURA = .Columns(2).Resize(CUENTA, C + 1)
        End With
        matriz = NFACTURA
        ReDim NUMEROS(CUENTA)
        Y = 1: SUMA = 0
        For i = 1 To CUENTA
            BOLETA = matriz(i, 2)
            matriz(i, 3) = Format(matriz(i, 3), "$ 0,0.00")
            CUENTA2 = X.CountIf(BOLETAS.Columns(1), BOLETA)
            VALIDA = CUENTA2 > 0
            If VALIDA Then
                FILA = X.Match(BOLETA, BOLETAS.Columns(1), 0)
                matriz(i, 4) = "EXISTE"
                VALIDA2 = Y = 1
                    If VALIDA2 Then
                        SUMA = BOLETAS.Cells(FILA, 3)
                    Else
                        SUMA = SUMA + BOLETAS.Cells(FILA, 3)
                    End If
                    Y = Y + 1
            Else
                matriz(i, 4) = "NO EXISTE"
            End If
        Next i
        With ListBox1
            .Clear
            .ColumnCount = C + 1
            .List = matriz
            .ColumnWidths = "80;80;80;80"
        End With
        With TextBox3
            .Text = Format(SUMA, "$ 0,0.00")
            .Locked = True
        End With
    End With
    End If
SAL:
    Set FACTURAS = Nothing: Set BOLETAS = Nothing
    Set NFACTURA = Nothing
    TextBox1.SetFocus
End Sub
Respuesta
1

No está demasiado clara tu definición.

Veamos, pones la foto de la Hoja1 y te refieres a ella como si fuera la segunda hoja.

Voy a suponer entonces que esa Hoja1 en realidad es la Hoja2. Y que la hoja1 tendría este aspecto.

Y voy a suponer también, basándome en lo que has escrito que solo quieres saber si en la segunda hoja (tu Hoja1) existe esa boleta. Entonces solamente habría que poner un SI o un NO.

La fórmula entonces sería la de la columna C de esta foto (suponiendo que la boleta de la segunda hoja esté en la columna A)

=SI(CONTAR.SI(Hoja2!$A$2:$A$20;B2)>0;"SI";"NO")

Si no es eso lo que buscas, aporta más información.

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas