简体   繁体   中英

VBA excel - loop in a loop

First of all, i'd like to point out im a beginner in VBA excel coding. I can't seem to know how to code a loop in a loop for the following problem: My excel has in column D the following info: D2:12, D3:12, D4:5

and im trying to automate column E as following: E1 to E12 would be the information in D2, E13 to E25 would be the information in D3. etc... up to a certain established threshold.

I currently have coded the following:

Sub salairemensuelle()

Dim xrow As Integer, xcol As interger, n As Integer, nbrdecolonnedemois As Integer 

xrow = 2 

xcol = 4

Do Until Cells(xrow, xcol).Value >= 25 'threshold of 25
        n = Range("D65536").End(xlUp).Row 'finding row of D column
        For nbrdecolonnedemois = 1 To n

End Sub

I seem to be stuck here since i dont know how to loop the first D column and then closing both loops.

Could anybody take a look. Thanks

I don't think you need two loops for this. Neither of your loops are closed, though.

You close a Do with Loop , (or Loop While , etc.) eg,:

Do Until i >= 10

    i = i+1

Loop

You create a For loop with the Next statement, eg, :

For i = 1 to 10
    MsgBox i
Next

In your case, I think you can just use a For ... Next loop with an Exit For statement when the threshold condition obtains:

Sub salairemensuelle()

Dim xrow As Integer, xcol As interger, n As Integer, nbrdecolonnedemois As Integer 

xrow = 2 
xcol = 4

        n = Range("D65536").End(xlUp).Row 'finding row of D column
        For nbrdecolonnedemois = 1 To n
            'The next line terminates the loop if threshold of 25 is met:
            If Cells(xrow, xcol).Value >= 25 Then 
                Exit For
            Else:
                '### The rest of your code operates inside this ELSE block
            End If

        Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM