Search code examples
vbaexcelrangecopy-paste

Copy paste values within cell range


Following on from my previous question, I would now like to copy paste values within a cell range.

The code used in my previous query was;

Sub CopyYesInW()
Dim lastRow As Long, i As Long
'determine last row in column W
lastRow = Cells(Rows.Count, "W").End(xlUp).Row
For i = 1 To lastRow
    'if Yes in W then copy from P to W in current row
    If Cells(i, "W").Value = "Yes" Then
        Cells(i, "P").Value = Cells(i, "P").Value
    End If
    If Cells(i, "W").Value = "Yes" Then
        Cells(i, "U").Value = Cells(i, "U").Value
    End If
Next
End Sub

I have amended the code in the script below to check the the cell range C6:N6 for values = Yes then copy paste values over the cells in C9:N9. However I am not sure what I am doing wrong. There is a runtime error '5' invalid procedure call or argument

Sub CopyYesInForecast()
Dim lastRow As Long, i As Long
'determine last row in column W
lastRow = Cells("C6")
For i = 1 To lastRow
'if Yes in W then copy from P to W in current row
    If Cells(i, "C6:N6").Value = "Yes" Then
        Cells(i, "C9:N9").Value = Cells(i, "C9:N9").Value
    End If
Next
End Sub

Solution

  • While your narrative is thin, perhaps this is close to what you are attempting.

    Sub CopyYesInForecast()
        Dim c As Long
    
        For c = range("C:C").column to range("N:N").column
            If Cells(6, c).Value = "Yes" Then
                Cells(9, c) = Cells(6, c).Value
            End If
        Next
    End Sub
    

    This looks through row 6, column C to N and if it finds Yes then it transfers the value to the same column in row 9.