Fitting numbers into cell range

BKGLTS

Board Regular
Joined
Aug 27, 2018
Messages
82
Hello,

Is there a method/formula,function that would calculate the minimum numbers to add to a row range to equal a certain target value?

For example:

Say I have a ten cell range A1:A10.
I have a target value of 15.
I need the solution to fill as many cells, starting from A1, as it can with 1's and then switch to 2's and 3's and so on, with the goal of achieving the target number with the smallest number values.

So, the desired result would be:
A1=1
A2=1
A3=1
A4=1
A5=1
A6=2
A7=2
A8=2
A9=2
A10=2
<strike>
</strike>
The sum of all the cells equals 15, but uses the lowest numbers possible to achieve it.
Once the number increases it cannot decrease again.

Another example with target number of 17:
A1=1
A2=1
A3=1
A4=1
A5=1
A6=2
A7=2
A8=2
A9=3
A10=3

Thank you!
B
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
Why would a target of 17 be like you posted instead of :

A1=1
A2=1
A3=1
A4=2
A5=2
A6=2
A7=2
A8=2
A9=2
A10=2

Or :

A1=1
A2=1
A3=1
A4=1
A5=2
A6=2
A7=2
A8=2
A9=2
A10=3

<colgroup><col></colgroup><tbody>
</tbody>


<colgroup><col></colgroup><tbody>
</tbody>
 
Upvote 0
Enter the target value in B1 and :
Code:
Sub FT()
Dim rng As Range, targetN%, low%, r%
Set rng = [A1:A10]
targetN = [B1]
low = Int(targetN / rng.Count)
rng = low
For r = rng.Count To 1 Step -1
    If Application.WorksheetFunction.Sum(rng) = targetN Then Exit For
    rng(r) = low + 1
Next
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,832
Messages
6,121,844
Members
449,051
Latest member
excelquestion515

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top