0

I'm trying to make a loop through lines to read each time a cell, and write into another sheet.

Sub boucle_for()
    Dim col As Integer
    Dim lig As Integer
    Dim rr As Integer
    Dim cc As Integer

    col = 4
    lig = 3
    rr = 15
    cc = 24

    For i = 0 To 33
        Range("R[" & col & "]C[" & lig & "]").Formula = "=AVG('Weekly Changes'!R[" & rr & "]C[" & cc & "]:R[" & (rr + 1) & "]C[" & (cc + 1) & "])"
        rr = rr + 14
        lig = lig + 1
    Next
End Sub

My aim is to refer to a cell dynamically, but the VBA script says it's an error. I'm used to Java and JavaScript arrays, but I'm failing at this.

Where did I make a mistake?

1 Answer 1

1

I always prefer to use the Cells class (using the R1C1 reference) method, like this:

Cells(rr, col).Formula = ...

If you need a multi-cell range, you do something like this:

Range(Cells(rr, col), Cells(rx, colx)).Formula = ...

But you could also do this:

Range("A5").Formula = ...

Some people will make function to turn the column number into the letter. I think it's tacky, but it would look like this:

Range(MyNumberToLetterFunction(col) & rr).Formula = ...

or a mulit-cell range:

Range("A5:B6").Formula = ...

By the way, it's good practice to qualify your ranges using a sheet reference. It seems to work very well with loops, like you're doing:

Sheet1.Cells(rr, col).Value = ...

Or

Sheets("My Awesome Stuff").Cells(rr, col).Value = ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.