Forum Discussion

JennaSmith495's avatar
JennaSmith495
Copper Contributor
Sep 13, 2021
Solved

Using VBA to take the data from a column and space it out into a row with 4 empty cells in between

I am trying to write code in VBA to take a column of data from one sheet and move it to one row in another sheet, but I also want there to be four empty cells in between each value in the row. The co...
  • HansVogelaar's avatar
    Sep 13, 2021

    JennaSmith495 

    Here you go. Modify the constants at the beginning for your setup.

    Sub CopyAndSpace()
        ' Change the following as needed
        Const SourceSheet = "Sheet1"
        Const FirstSourceRow = 1
        Const SourceCol = "C"
        Const TargetSheet = "Sheet2"
        Const TargetRow = 2
        Const Interval = 5
        ' Variables
        Dim WSource As Worksheet
        Dim WTarget As Worksheet
        Dim SourceRow As Long
        Dim LastSourceRow As Long
        Dim TargetCol As Long
        ' Code to copy cells
        Application.ScreenUpdating = False
        Set WSource = Worksheets(SourceSheet)
        Set WTarget = Worksheets(TargetSheet)
        LastSourceRow = WSource.Cells(WSource.Rows.Count, SourceCol).End(xlUp).Row
        For SourceRow = FirstSourceRow To LastSourceRow
            TargetCol = TargetCol + Interval
            WTarget.Cells(TargetRow, TargetCol).Value = WSource.Cells(SourceRow, SourceCol).Value
        Next SourceRow
        Application.ScreenUpdating = True
    End Sub

Resources