I have developed a code like this
For i = 1 To 50
For j = i + 1 To 50
For k = j + 1 To 50
..........................
'Here I have someother code
..........................
Next k
Next j
Next i
So this is a nested for loop. And there are 3 for loops in this code. Now what I want is, I want to make the number of for loops a variable. For an example I have variable call NumberOfForLoops. So if NumberOfForLoops=3 then there should be 3 for loops. If NumberOfForLoops=8 then there should be 8 for loops. I can't find how to do this.
I think it is better to explain what I was trying to accomplish.
I'm trying to find possible combinations
For 3 combinations I wrote this code
Dim WS_Data As Worksheet
Dim WS_Result As Worksheet
Set WS_Data = Worksheets("Data")
Set WS_Result = Worksheets("Result")
Dim i As Long
Dim j As Long
Dim k As Long
Dim EnteringRow As Long
EnteringRow = 1
For i = 1 To 5
For j = i + 1 To 5
For k = j + 1 To 5
WS_Result.Range("A" & EnteringRow).Value = WS_Data.Range("A" & i).Value
WS_Result.Range("B" & EnteringRow).Value = WS_Data.Range("A" & j).Value
WS_Result.Range("C" & EnteringRow).Value = WS_Data.Range("A" & k).Value
EnteringRow = EnteringRow + 1
Next k
Next j
Next i
It gave me below result
But now what I need is I want to make the number of items I select from the list dynamic. According to the anwers I understood that I need to use a recursion concept. So I modified the code according to h2so4's answer.
This is the modified code
Sub test()
Dim WS_Data As Worksheet
Dim WS_Result As Worksheet
Dim WS_Temp As Worksheet
Set WS_Data = Worksheets("Data")
Set WS_Result = Worksheets("Result")
Set WS_Temp = Worksheets("Temp")
ResultRow = 1
NofL = 3
Nestedloop WS_Data, WS_Result, WS_Temp, ResultRow, NofL, 1, 5, 1
End Sub
Sub Nestedloop(WS_Data, WS_Result, WS_Temp, ResultRow, NofL, jmin, jmax, level)
For j = jmin To jmax
WS_Temp.Cells(1, level) = j
'your code when a value of j is set
If level < NofL Then
Nestedloop WS_Data, WS_Result, WS_Temp, ResultRow, NofL, jmin + 1, jmax, level + 1
Else
'your code when the number of loops is reached
For i = 1 To NofL
WS_Result.Cells(ResultRow, 0 + i).Value = WS_Data.Range("A" & WS_Temp.Cells(1, i).Value).Value
Next i
ResultRow = ResultRow + 1
End If
Next j
End Sub
I used a tempory sheet. This is the result I got.
Difficult to understand what is wrong.