Encontrar X cantidad de números dentro una lista que sumen un importe Y

Anónimas
2022-03-11T14:13:42+00:00

Hola buenos días, antes que nada quisiera aclarar que no sé si la solución para agilizar este proceso sea un macro, una fórmula, una regla, o algo diferente. Esta consulta sirve para pagos a proveedores con cheques de terceros, nos serviría para agilizar el proceso de buscar qué cheques de terceros usar para pagarle a un proveedor. Les doy un ejemplo:

Tenemos que pagarle a un proveedor $810.000,00, y en nuestra cartera de cheques contamos con los siguientes cheques de terceros:

$ 10.000,00

$ 74.764,00

$ 75.410,90

$ 100.000,00

$ 104.700,00

$ 104.751,13

$ 105.000,00

$ 105.703,04

$ 106.000,00

$ 196.684,00

$ 198.720,00

$ 198.721,00

$ 198.722,00

$ 200.000,00

$ 202.579,26

$ 205.583,75

$ 568.979,57

$ 600.000,00

$ 602.500,00

$ 603.405,29

(En realidad son más, en total más de 250 cheques todos con diferentes importes, pero no coloqué todos para simplificar el ejemplo).

Lo que necesito hacer es juntar X cantidad de cheques para pagarle a este proveedor: en este caso, usaría los cheques de $600.000,00, $200.000,00 y $10.000,00.

Entonces, lo que necesito es una macros/fórmula/regla/lo que sea, que me busque automáticamente cuáles cheques puedo usar para pagarle al proveedor. O al menos que me encuentre la suma de cheques que más se aproxime al resultado objetivo (en este caso fue $810.000,00, pero casi nunca es exacto).

Otro ejemplo que les puedo dar es un proveedor al cual le tenemos que pagar $1.011.695,78. Con la misma cartera de cheques, yo lo que haría es usar los cheques de $600.000,- + $200.000,- + $106.000,- + $105.703,04. Esta suma da un total de $1.011.703,04, pero sería la que más se aproxima al total que tengo que pagar, y me serviría perfectamente.

Cualquier cosa si no se entendió algo me preguntan.

Muchas gracias por su ayuda.

Microsoft 365 y Office | Excel | Para el negocio | Windows

Pregunta bloqueada. Esta pregunta se migró desde la Comunidad de Soporte técnico de Microsoft. Puede votar si es útil, pero no puede agregar comentarios o respuestas ni seguir la pregunta.

0 comentarios No hay comentarios

24 respuestas

Ordenar por: Muy útil
  1. Héctor Miguel 71,520 Puntos de reputación
    2022-03-23T02:20:19+00:00

    lo mas interesante de este hilo, es que OP no ha vuelto (ni aqui, ni alla donde tambien pregunto)

    y si tu memoria y tiempo andan a ese nivel ?... (no puedo ayudarte mas) 😮

    ¿Le ha resultado útil esta respuesta?

    1 persona ha encontrado útil esta respuesta.
    0 comentarios No hay comentarios
  2. Héctor Miguel 71,520 Puntos de reputación
    2022-03-13T15:45:53+00:00

    esa fue "la sencilla" (y no viste lo adicional)

    mejor ni te menciono de la "menos sencilla" (va un poco mas alla de =1+1) 😎

    ademas de que tambien es posible SIN vba ✌️

    ¿Le ha resultado útil esta respuesta?

    0 comentarios No hay comentarios
  3. Anónimas
    2022-03-13T09:56:00+00:00

    Una vez estirado tu código, leído y probado, creo que mi código es, además de más claro, mejor y más flexible que el tuyo, por esto:

    a) se le puede añadir que se marquen (en una columna anexa) las cantidades ya utilizadas para que no se vuelvan a utilizar en sucesivas ejecuciones.

    b) se puede fácilmente modificar para definir el límite inferior y superior del margen admitido.

    c) fuerza a utilizar el menor número posible de cheques, pero podría invertirse para forzar a utilizar el mayor número posible de cheques).

    Le he hecho algunas mejoras de poca importancia.

    ¿Le ha resultado útil esta respuesta?

    0 comentarios No hay comentarios
  4. Héctor Miguel 71,520 Puntos de reputación
    2022-03-13T04:46:26+00:00

    Aquí tienes una solución para un máximo de cuatro cheques. ¿Alguien se atreve a hacerlo recursivo?

    esta la tengo desde +/- 2003:

    Private objetivo As Double, optimo As Double, nVals As Integer, prueba() As Integer, confirma() As Integer, valores

    Private Function Evalua(ByVal suma As Double, ByVal pos As Integer): Dim n As Integer

    If pos <= nVals Then

    prueba(pos) = 0: Evalua suma, pos + 1: prueba(pos) = 1: Evalua suma + valores(pos), pos + 1 
    

    Else

    If (Abs(suma - objetivo) &lt; Abs(objetivo - optimo)) Then 
    
      optimo = suma: For n = 1 To nVals: confirma(n) = prueba(n): Next: End If: End If: End Function 
    

    Function cualesSuman(cuanto As Double, donde As Range, Optional referencia As Boolean = True) As String

    With Application.WorksheetFunction

    If cuanto &lt; .Min(donde) Then cualesSuman = "cantidad inferior al valor minimo !!!": Exit Function 
    
    If cuanto &gt; .Sum(donde) Then cualesSuman = "cantidad superior a la suma total !!!": Exit Function 
    

    End With: Dim tmp As String, n As Integer: optimo = 0: objetivo = cuanto

    With donde.Columns(1): nVals = .Rows.Count: valores = Application.Transpose(.Value)

    ReDim prueba(nVals): ReDim confirma(nVals): Evalua 0, 1: For n = 1 To nVals 
    
      If confirma(n) Then tmp = tmp & "+" & IIf(referencia, .Cells(n).Address(0, 0), .Cells(n)) 
    
    Next: End With: If tmp = "" Then cualesSuman = "sumandos NO localizados !!!": Exit Function 
    

    cualesSuman = IIf(Evaluate(tmp) <> objetivo, "aproximado: " & Evaluate(tmp) & " ", "") & "=" & Mid(LCase(tmp), 2)

    End Function

    ¿Le ha resultado útil esta respuesta?

    0 comentarios No hay comentarios
  5. Anónimas
    2022-03-11T16:00:07+00:00

    Aquí tienes una solución para un máximo de cuatro cheques. ¿Alguien se atreve a hacerlo recursivo?

    Imagen

    Option Explicit

    Dim UF As Integer

    Sub Cheques()

    ' selecciona hasta cuatro cheques para pagar un importe (importe en celda B1) 
    
    ' se admite un margen en más o en menos (margen en celda E1) 
    
    ' la relación de cheques iniciales debe estar ordenada de menor a mayor (columna 1, desde A3) 
    
    ' la salida de los cheques elegidos en columna 4 desde D3 
    
    Dim MargenAdmitido As Double 
    
    Dim Objetivo As Double 
    
    Objetivo = Cells(1, 2) 
    
    MargenAdmitido = Cells(1, 5) 
    
    UF = Cells(10000, 1).End(xlUp).Row 
    
    Range("b3:d" & UF).Clear 
    
    ElegirUncheque Objetivo + MargenAdmitido, Objetivo - MargenAdmitido 
    

    End Sub

    Sub ElegirUncheque(ImporteMaximo As Double, ImporteMinimo As Double)

    Dim i As Integer 
    
    Dim f As Integer 
    
    Dim EncontradaSolucion As Boolean 
    
    Dim UF2 As Integer 
    
    Dim UF3 As Integer 
    
    Const N As Integer = 1 
    
    UF = Cells(10000, N).End(xlUp).Row          ' última fila columna cheques iniciales 
    
    UF2 = Cells(10000, N + 1).End(xlUp).Row + 1 ' última fila columna chiques disponibles 
    
    UF3 = Cells(10000, 4).End(xlUp).Row + 1 ' ultima fila columna de cheques elegidos 
    
    ' genero los cheques utilizables 
    
    f = 3 
    
    For i = 3 To UF 
    
        If Cells(i, N) &gt; ImporteMaximo Then 
    
            Exit For ' supongo la lista de cheques ordenada ascendente 
    
        Else 
    
            Cells(f, N + 1) = Cells(i, N) 
    
            f = f + 1 
    
        End If 
    
    Next i 
    
    ' busco si en esa lista tenemos un cheque que cumpla la condición 
    
    For i = 3 To UF 
    
        If Cells(i, N + 1) &gt;= ImporteMinimo And Cells(i, N + 1) &lt;= ImporteMaximo Then 
    
            Range("D" & UF3) = Cells(i, N + 1) 
    
            EncontradaSolucion = True 
    
            Exit Sub 
    
        End If 
    
    Next i 
    
    ElegirDoscheques ImporteMaximo, ImporteMinimo 
    

    End Sub

    Sub ElegirDoscheques(Imax As Double, Imin As Double)

    Dim i As Integer 
    
    Dim j As Integer 
    
    Dim PrimerCheque As Double 
    
    Dim EncontradaSolucion As Boolean 
    
    Dim UF2 As Integer 
    
    Dim UF3 As Integer 
    
    Const N As Integer = 1 
    
    UF2 = Cells(10000, N + 1).End(xlUp).Row + 1 ' última fila columna cheques disponibles 
    
    UF3 = Cells(10000, 4).End(xlUp).Row + 1 ' ultima fila columna de cheques elegidos 
    
    For i = 3 To UF2 
    
        PrimerCheque = Cells(i, 2) 
    
        For j = i + 1 To UF2 
    
            If Cells(j, 2) &gt; Imax - PrimerCheque Then 
    
                Exit For  ' no sigo leyendo porque todos los demás exceden 
    
            End If 
    
            If PrimerCheque + Cells(j, 2) &gt;= Imin And PrimerCheque + Cells(j, 2) &lt;= Imax Then 
    
                Range("D" & UF3) = PrimerCheque 
    
                Range("D" & UF3 + 1) = Cells(j, 2) 
    
                EncontradaSolucion = True 
    
                Exit Sub 
    
            End If 
    
        Next 
    
    Next i 
    
    ElegirTresCheques Imax, Imin 
    

    End Sub

    Sub ElegirTresCheques(Imax As Double, Imin As Double)

    Dim i As Integer 
    
    Dim j As Integer 
    
    Dim k As Integer 
    
    Dim PrimerCheque As Double 
    
    Dim SegundoCheque As Double 
    
    Dim Parcial As Double 
    
    Dim EncontradaSolucion As Boolean 
    
    Dim UF2 As Integer 
    
    Dim UF3 As Integer 
    
    Const N As Integer = 1 
    
    Dim Res As String 
    
    UF2 = Cells(10000, N + 1).End(xlUp).Row + 1 ' última fila columna cheques disponibles 
    
    UF3 = Cells(10000, 4).End(xlUp).Row + 1     ' ultima fila columna de cheques elegidos 
    
    For i = 3 To UF2 
    
        PrimerCheque = Cells(i, 2) 
    
        For j = i + 1 To UF2 
    
            SegundoCheque = Cells(j, 2) 
    
            Parcial = PrimerCheque + SegundoCheque 
    
            For k = j + 1 To UF2 
    
                If Cells(k, 2) &gt; Imax - Parcial Then 
    
                    Exit For  ' no sigo leyendo porque todos los demás exceden 
    
                End If 
    
                If Parcial + Cells(k, 2) &gt;= Imin And Parcial + Cells(k, 2) &lt;= Imax Then 
    
                    Range("D" & UF3) = PrimerCheque 
    
                    Range("D" & UF3 + 1) = SegundoCheque 
    
                    Range("D" & UF3 + 2) = Cells(k, 2) 
    
                    EncontradaSolucion = True 
    
                    Exit Sub 
    
                End If 
    
            Next k 
    
        Next j 
    
    Next i 
    
    ElegirCuatroCheques Imax, Imin 
    

    End Sub

    Sub ElegirCuatroCheques(Imax As Double, Imin As Double)

    Dim i As Integer 
    
    Dim j As Integer 
    
    Dim k As Integer 
    
    Dim m As Integer 
    
    Dim PrimerCheque As Double 
    
    Dim SegundoCheque As Double 
    
    Dim TercerCheque As Double 
    
    Dim Parcial As Double 
    
    Dim EncontradaSolucion As Boolean 
    
    Dim UF2 As Integer 
    
    Dim UF3 As Integer 
    
    Const N As Integer = 1 
    
    Dim Res As String 
    
    UF2 = Cells(10000, N + 1).End(xlUp).Row + 1 ' última fila columna cheques disponibles 
    
    UF3 = Cells(10000, 4).End(xlUp).Row + 1     ' ultima fila columna de cheques elegidos 
    
    For i = 3 To UF2 ' primer chique 
    
        PrimerCheque = Cells(i, 2) 
    
        For j = i + 1 To UF2  ' segundo cheque 
    
            SegundoCheque = Cells(j, 2) 
    
            Parcial = PrimerCheque + SegundoCheque 
    
            For k = j + 1 To UF2   ' tercer cheque 
    
                If Cells(k, 2) &gt; Imax - Parcial Then 
    
                    Exit For  ' no sigo leyendo porque todos los demás exceden 
    
                End If 
    
                TercerCheque = Cells(k, 2) 
    
                Parcial = PrimerCheque + SegundoCheque + TercerCheque 
    
                For m = k + 1 To UF2  ' cuarto cheque 
    
                    If Cells(m, 2) &gt; Imax - Parcial Then 
    
                        Exit For  ' no sigo leyendo porque todos los demás exceden 
    
                    End If 
    
                    If Parcial + Cells(m, 2) &gt;= Imin And Parcial + Cells(m, 2) &lt;= Imax Then 
    
                        Range("D" & UF3) = PrimerCheque 
    
                        Range("D" & UF3 + 1) = SegundoCheque 
    
                        Range("D" & UF3 + 2) = TercerCheque 
    
                        Range("D" & UF3 + 3) = Cells(m, 2) 
    
                        EncontradaSolucion = True 
    
                        Exit Sub 
    
                    End If 
    
                Next m 
    
            Next k 
    
        Next j 
    
    Next i 
    
    Res = MsgBox("No encontrada solución ", vbInformation) 
    

    End Sub

    ¿Le ha resultado útil esta respuesta?

    0 comentarios No hay comentarios