How to use nested loop for a Matrix cell in excel

2019-07-25 05:38发布

Current Excel Sheet Structure

filteredStartRow = A2 detailsStartRow = D2

※i = x(get value for filteredItemCount, e.g: 2, 3, 2)
※j = y(get value for detailsItemCount, e.g: 4, 5, 3)

I am stuck, how efficiently I can move to second filteredStartRow (A4) and detailsStartRow (D10). and continue until the last filter and details StartRow.

What I am doing: Get ItemCount (e.g: x, y) to run the nested loop within filter and details item. Since I already know the next item count for filter and details, so I just need to change my NEXT filterStartRow and detailsStartRow. How can construct my Loop using any dynamic settings for (i, j) as well as setting up STARTROW? Can anyone please help with code.

Here is my code, which only works for the very first loop (green bordered).

startRow = 2
startRow1 = 2
nextDetailsRow = 0

For i = 1 To noOfFilteredItem (e.g:3)

mapFilteredItemCount = Worksheets("Sheet1").Cells(startRow, 3).Value
detailsItemCount = Worksheets("Sheet1").Cells(startRow1, 6).Value

With ThisWorkbook.Worksheets("Sheet1")
For m = 1 To mapFilteredItemCount 
For n = 1 To detailsItemCount 
If .Cells((startRow + m) - 1, 2) = .Cells((startRow1 + n) - 1, 5) Then
If IsEmpty(.Cells((startRow1 + n) - 1, 8).Value) = True Then
.Cells((startRow1 + n) - 1, 8).Value = "Deliver"
nextDetailsRow = nextDetailsRow + startRow + n
Else
GoTo NextIteration
End If
End If
NextIteration:

Next n
Next m
End With
Next i

My Problem is:
- I need to update the STARTROW and STARTROW1 dynamically once a loop (m, n) is completed.
- How can I assign STARTROW and STARTROW1 variable to receive next starting row value.

My Logic:
- I was thinking to keep all the STARTROW and STARTROW1 number into an array, then get value from the array.
for example:
filteredItemRowArray() = 2, 4, 7 (※starting row numbers for filtered item)
detailsItemRowArray() = 2, 6, 11 (※starting row numbers for details item)

but I could not arrange this array to keep row number values.

Could anyone please help me, I truly appreciate your programming SMARTNESS. If you have any questions, or understanding problem, please let me know. Thank you very much.

1条回答
Melony?
2楼-- · 2019-07-25 06:08

I would try the same idea. Looping through an array with the numbers. Please try the following code:

Sub Outer_Loop()
Dim StartrowArr, Startrow1Arr, I As Integer
Dim Startrow As Long, Startrow1 As Long
StartrowArr = Array(2, 4, 7)
Startrow1Arr = Array(2, 6, 11)
For I = LBound(StartrowArr) To UBound(StartrowArr)
    Startrow = StartrowArr(I)
    Startrow1 = Startrow1Arr(I)
    Debug.Print "Loop " & I, "Startrow: " & Startrow, "Startrow1: " & Startrow1
    ' your code
Next I
End Sub
查看更多
登录 后发表回答