I try to generate all possible combinations which equal to a given sum
In this case I give:
Min = 0, Max = 1, Step = 0.01, Sum = 1 and nAssets equal to 3
I want Min, Max, Step, sum and nAssets to be dynamic by using two dimensional arrays, but My for loop did not work out.
Here is the part of solution that I want:
In this case I give:
Min = 0, Max = 1, Step = 0.01, Sum = 1 and nAssets equal to 3
I want Min, Max, Step, sum and nAssets to be dynamic by using two dimensional arrays, but My for loop did not work out.
Here is the part of solution that I want:
VBA Code:
Sub combination()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim i As Long, r As Long, A As Long, nAssets As Long
Dim value As Long
Dim nSim As Long: nSim = 1
Dim nSimStep As Long
nAssets = Range("A1").value
Dim AllocArray() As Variant
ReDim AllocArray(1 To nAssets, 1 To 3)
Total = Range("Total").value
'----Collect Min, Max, Step as two dimension arrays----
For i = 1 To nAssets
AllocArray(i, 1) = Range("Min").Offset(i - 1).value
AllocArray(i, 2) = Range("Max").Offset(i - 1).value
AllocArray(i, 3) = Range("Step").Offset(i - 1).value
Next i
For i = 1 To nAssets Step 1
nSimStep = (AllocArray(i, 2) - AllocArray(i, 1)) / AllocArray(i, 3)
nSim = nSim * nSimStep
Next i
Dim Param() As Variant
ReDim Param(1 To nSim, 1 To nAssets)
Dim sum() As Variant
ReDim sum(1 To nSim)
A = 1
For n = 1 To nAssets Step 1
For value = AllocArray(n, 1) To AllocArray(n, 2) Step AllocArray(n, 3)
Param(A, n) = Round(value, 2)
sum(A) = sum(A) + Param(A, n)
If sum(A) = Total Then
Cells(A - 1, n - 1).value = Param(A, n)
A = A + 1
End If
Next value
Next n
Application.Calculation = xlCalculationAutomatic
End Sub