Search code examples
excelvbaloopscopy-paste

VBA Loop - copy and paste cells into next column until cell x equals cell y


I need some help looping. I have not used VBA for sometime and starting to learn again. I remember this community helped me a lot in the past so any help is appreciated.

The Challenge

I want to copy cell H12 into the next empty column starting with i12 then J12 and so forth. So I want to continue the loop until the the number of pasted arrays equal the number in cell D12. So if Cell D12 = 20 I want to continue this loop copying H12 until I get to AB12.

Then once this is complete I want to move to the next row H13 and do the same thing. In this case D13 = 15 so we do the same as above copying H13 until we get to R13.

Any help is really appreciated. I have tried some loops for other things which have not worked out.


Solution

  • Under the assumption, that your selected cell is H12 and the cells right of it are empty and D12 is filled with a positive numeric value, the following code should work:

    Sub CopyToRange()
    
    Dim ThisCol As Integer, ThisRow As Long, CurS As Worksheet, CurRg As Range, InfCol As Integer
    
    Set CurS = ActiveSheet
    ThisRow = ActiveCell.Row
    ThisCol = ActiveCell.Column
    InfCol = 4 'column 'D'
    Set CurRg = Range(CurS.Cells(ThisRow, ThisCol + 1), CurS.Cells(ThisRow, ThisCol + CurS.Cells(ThisRow, InfCol).Value))
    ActiveCell.Copy
    CurRg.PasteSpecial (xlPasteAll)
    
    End Sub
    

    If you select the next row with the same preconditions it will work as well