user1996971
user1996971

Reputation: 543

Is it possible to have a single line of a VBA script repeat "N" number of times?

I'm experimenting with recursive for the first time. In this problem, I have a huge dataset with many rows, and in each row, there's N number of 4 cell ranges to copy (from column O to column GB). I have the following function written:

Function Recursive(Rng As Range)

If N = 1 Then

Rng.Offset(, -3).Resize(, 670).Copy
Rng.Offset(1, -3).Insert Shift:=xlDown
Rng.Offset(, 6).Resize(, 4).Copy
Rng.PasteSpecial Paste:=xlPasteValues

Else
Rng.Offset(, -2).Resize(, 670).Copy
Rng.Offset(1, -2).Insert Shift:=xlDown 'Repeat these two lines N times'

Rng.Offset(, 7 + 4 * N).Resize(, 3).Copy
Rng.Offset(N, 0).PasteSpecial Paste:=xlPasteValues
Recursive (N - 1)
End If
N = 0
End Function

I know it's pretty rough, and I see some problems already. Basically, if N is equal to 4, then I want the first two lines of the Else instruction to be repeated 4 times, then move on to carry out the next three lines over and over until N is equal to 1. Basically, where there are many ranges going across the dataset, I want to create a new line to put them into, including the cells to the left of Rng. Is it possible to put in a line where I've made my comment, that says "Go back and repeat these two lines N times?"

Upvotes: 0

Views: 767

Answers (1)

Grade 'Eh' Bacon
Grade 'Eh' Bacon

Reputation: 3823

To elaborate on @MarcB's comment, there are many types of loops. I've chosen to do one main loop which reduces N by 1 until N = 0. Within that loop, if N = 1, then your special N = 1 code runs; otherwise if N = 4, it loops 4 times over that section of code, otherwise it runs your 'else' block of code.

Function Recursive(Rng As Range)

Dim OriginalN as Integer

OriginalN = N

While N <> 0

If N = 1 Then

    Rng.Offset(, -3).Resize(, 670).Copy
    Rng.Offset(1, -3).Insert Shift:=xlDown
    Rng.Offset(, 6).Resize(, 4).Copy
    Rng.PasteSpecial Paste:=xlPasteValues

ElseIf N = OriginalN Then
    For x = 1 To OriginalN
        Rng.Offset(, -2).Resize(, 670).Copy
        Rng.Offset(1, -2).Insert Shift:=xlDown 'Repeat these two lines N times'
    Next x
Else
    Rng.Offset(, 7 + 4 * N).Resize(, 3).Copy
    Rng.Offset(N, 0).PasteSpecial Paste:=xlPasteValues
    Recursive (N - 1)
End If

N = N - 1

Wend

End Function

You refer to 'going back' and redoing code, but using a GoTo statement is often considered sloppy if there are other methods available, as without proper care GoTo statements can run incorrectly/indefinately, and are somewhat harder to read.

Upvotes: 1

Related Questions