Consulting

Results 1 to 3 of 3

Thread: Solved: VBA loop through columns with relative referencing

  1. #1
    VBAX Regular
    Joined
    Dec 2012
    Posts
    12
    Location

    Solved: VBA loop through columns with relative referencing

    Hello everybody, I am a brand-new member and most importantly a very fresh coder dealing with my first nested loops.
    the aim of my macro is to calculate the ln return of some data in different columns.
    For this reason I need to loop through the rows of a single column, apply the Ln formula and then move to the next column.
    since I use relative referencing offsetting + and - columns I cannot get the right way to run my simple macro correctly.

    first of all lets assume I have some data in columns 1 to 3 and need to apply my formula and display the results in column 4 to 6.
    therefore my active cell, or better my starting point is cell D1.
    The first loop through rows of a single column should be like this:

    Sub Lnreturns()
        Range("D1").Select
            Do While ActiveCell.Offset(1, -3) <> ""
                ActiveCell.Offset(1, 0).Value = WorksheetFunction.Ln _
                (ActiveCell.Offset(1, -3) / ActiveCell.Offset(0, -3))
                ActiveCell.Offset(1, 0).Select
            Loop
    End Sub
    
    Now
    the next step should be to insert a For/Next loop in order to change column.
    like:
     For c=1 to 3     
            Do While ActiveCell.Offset(1, -c) <> ""
    'the rest of the code....
     next c
    the thing is that since I am adding and subtracting column to my active cell
    I cannot find the right way to use this loop
    Apologies for the lack of elegance in my code.
    Ty for your help
    Last edited by Bob Phillips; 12-16-2012 at 11:41 AM. Reason: Added VBA tags

  2. #2
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,876
    You can use the likes of:
    Cells(1,4).Select
    instead of:
    Range("D1").Select
    [Cells uses Cells(RowNo,ColumnNo)]
    So for the sake of the exercise your outer loop can be
    For c = 4 to 6
    leaving:[vba]Sub Lnreturns()
    For c = 4 To 6
    Cells(1, c).Select
    Do While ActiveCell.Offset(1, -3) <> ""
    ActiveCell.Offset(1, 0).Value = WorksheetFunction.Ln(ActiveCell.Offset(1, -3) / ActiveCell.Offset(0, -3))
    ActiveCell.Offset(1, 0).Select
    Loop
    Next c
    End Sub[/vba]
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

  3. #3
    VBAX Regular
    Joined
    Dec 2012
    Posts
    12
    Location
    That's exactly what I was looking for!
    Thanks a lot p45cal for the quick and clever answer.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •