'Begin loop with end of previous loop (Excel vba - For Loop)
I have following code
Sub Example()
Dim l1 As Integer
Dim l2 As Integer
Dim l3 As Integer
For l3 = 1 To 2
For l1 = 1 To 2
For l2 = 8 To 9
MsgBox l1 & "-" & l2
Next l2
Next l1
Next l3
End sub
Output: 1-8,1-9,2-8,2-9,1-8,1-9,2-8,2-9.
Need output: 1-8,1-9,2-8,2-9,1-8,1-9,2-8,2-9,10-18,10-19,11-18,11-19,10-18,10-19,11-18,11-19.
In l3 second loop take the max value increment with 1 of previous loop dynamicaly.
End Sub
Solution 1:[1]
Just repeat your loop changing values:
Sub Example()
Dim l1 As Integer
Dim l2 As Integer
Dim l3 As Integer
For l3 = 1 To 2
For l1 = 1 To 2
For l2 = 8 To 9
Debug.Print l1 & "-" & l2
Next l2
Next l1
Next l3
For l3 = 10 To 11
For l1 = 10 To 11
For l2 = 18 To 19
Debug.Print l1 & "-" & l2
Next l2
Next l1
Next l3
End Sub
Output:
1-8
1-9
2-8
2-9
1-8
1-9
2-8
2-9
10-18
10-19
11-18
11-19
10-18
10-19
11-18
11-19
This code it's easier to understand but you can make it shorter with an aditional loop and benefit from IIf:
Sub Example()
Dim l1 As Integer
Dim l2 As Integer
Dim l3 As Integer
Dim l4 As Integer
For l4 = 0 To 9 Step 9
For l3 = 1 To 2
For l1 = 1 To 2
For l2 = 8 To 9
Debug.Print l1 + l4 & "-" & l2 + IIf(l4 = 0, 0, 1 + l4)
Next l2
Next l1
Next l3
Next l4
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Foxfire And Burns And Burns |
