Sub btn_GetCombos_Click()
Dim rngNumbers As range
Dim i As Long, j As Long, k As Long
Dim colResults As New Collection
Dim arrResults() As String
Dim arrComboLoc As Variant
Dim LocIndex As Long
Dim dTot As Double
Dim str As String
Dim dTargetSum As Double
Dim bAdvanced As Boolean
Set rngNumbers = range("A2", Cells(Rows.Count, "A").End(xlUp))
range("F2:F" & Rows.Count).ClearContents
If Not IsNumeric(range("D2").Value) _
Or Len(Trim(range("D2").Value)) = 0 Then
range("D2").Select
MsgBox "Must provide a Target SUM number"
Exit Sub
End If
If Not IsNumeric(range("D3").Value) _
Or Len(Trim(range("D3").Value)) = 0 Then
range("D3").Select
MsgBox "Must provide the number of cells to use"
Exit Sub
ElseIf range("D3").Value > rngNumbers.Cells.Count Then
range("D3").Select
MsgBox "Number of cells may not exceed total amount of cells"
Exit Sub
ElseIf range("D3").Value < 1 Then
range("D3").Select
MsgBox "Number of cells may not be less than 1"
Exit Sub
End If
dTargetSum = range("D2").Value
arrComboLoc = Application.Transpose(Evaluate("Index(Row(1:" & range("D3").Value & "),)"))
On Error Resume Next
For i = 1 To WorksheetFunction.Combin(rngNumbers.Count, range("D3").Value)
dTot = 0
str = vbNullString
For LocIndex = LBound(arrComboLoc) To UBound(arrComboLoc)
dTot = dTot + rngNumbers.Cells(arrComboLoc(LocIndex)).Value
str = str & ", " & rngNumbers.Cells(arrComboLoc(LocIndex)).Value
Next LocIndex
If dTot <= dTargetSum Then
str = Mid(str, 3)
colResults.Add str, str
End If
bAdvanced = False
For j = UBound(arrComboLoc) To LBound(arrComboLoc) Step -1
If arrComboLoc(j) < rngNumbers.Cells.Count - (UBound(arrComboLoc) - j) Then
arrComboLoc(j) = arrComboLoc(j) + 1
For k = j + 1 To UBound(arrComboLoc)
arrComboLoc(k) = arrComboLoc(j) + k - j
Next k
bAdvanced = True
Exit For
End If
If bAdvanced = True Then Exit For
Next j
Next i
If colResults.Count > 0 Then
ReDim Preserve arrResults(1 To colResults.Count)
For i = 1 To colResults.Count
arrResults(i) = colResults(i)
Next i
range("F2").Resize(colResults.Count).Value = Application.Transpose(arrResults)
Else
MsgBox "No valid combinations found to be less than or equal to " & dTargetSum & " when using " & range("D3").Value & " cells."
End If
End Sub
Bookmarks