Search code examples
vbafor-looprangeoffset

Copy values from Range and paste each one with different given (row) offset in another sheet


First of all I would like to introduce myself. Iam Miguel and I recently started to learn VBA in order to improve and save time at work. I am familiar with formulas, all types, but when turning to VBA I get sometimes stuck.

I am trying to loop the range A2:A355 from Sheet"Aux" and copy each value to sheet "CS", and each value shall be pasted in Column A:A, but with the offset given in range B2:B355 Sheet "Aux". For Example I give the example attached. Sample Code:


This is the code:

Sub cablexsection() 
Dim s As Integer
Dim smax As Integer
smax = Sheets("Aux").Range("b1").Value

Sheets("CS").Activate

For s = 3 To smax
Sheets("CS").Cells(s, 1).Value = Sheets("Aux").Cells(s, 1).Value

'here I have to set the offset to down in order to paste cells given Sheets("Aux").Cells(s, 2) values

Next s

End Sub

And under the link you can find the file to be worked in:

Original File

Thank you very much and sorry if this question is repeated. I have tried to look through the forum but maybe I do not know what to write exactly.


Solution

  • Try this


    Option Explicit
    
    Sub CableXsection()
        Dim wsAux As Worksheet, wsCS As Worksheet
        Dim s As Long, sMax As Long, offSetCell As Range
    
        Set wsAux = ThisWorkbook.Worksheets("Aux")
        Set wsCS = ThisWorkbook.Worksheets("CS")
    
        sMax = wsAux.Range("B1").Value
    
        Application.ScreenUpdating = False
    
        For s = 3 To sMax
    
            Set offSetCell = wsAux.Cells(s, 2)    '2 is the offset column from the same row
    
            If Not IsError(offSetCell) And IsNumeric(offSetCell) Then
                wsCS.Cells(offSetCell.Value2 + s, 1).Value = wsAux.Cells(s, 1).Value
            End If
        Next
    
        Application.ScreenUpdating = True
    End Sub