Search code examples
vbaexcelexcel-2013

Copying Cell Value to another sheet in Excel with VBA


I have the following code which successfully copies cells B, E and F to cells B, C, D in sheet 2 after I match a string in another cell. The problem is that it copies the cell and not only just the value inside it (I don't need borders, colour etc).

Another issue I have is that while it will copy the data to the next free row in Column B, it won't look for the next free row according to column C and D.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim thisrow As Long
Dim lr As Long
If Target.Column = 7 Then
    thisrow = Target.Row
If Target.Value = "FAULTY" Then
    lr = Sheets("sheet2").Range("B" & Rows.Count).End(xlUp).Row + 1
    Range("B" & ActiveCell.Row).Copy Sheets("sheet2").Range("B" & lr)
    Range("D" & ActiveCell.Row).Copy Sheets("sheet2").Range("C" & lr)
    Range("F" & ActiveCell.Row).Copy Sheets("sheet2").Range("D" & lr)
End If
End If

End Sub

Solution

  • You can use the .Value operator instead. Also, just set a separate variable for the C/D Range for the next available cell.

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim thisrow As Long
        Dim lr As Long
        If Target.Column = 7 Then
            thisrow = Target.Row
            If Target.Value = "FAULTY" Then
                lr = Sheets("sheet2").Range("B" & Rows.Count).End(xlUp).Row + 1
                mr = Sheets("sheet2").Range("C" & Rows.Count).End(xlUp).Row + 1
                nr = Sheets("sheet2").Range("D" & Rows.Count).End(xlUp).Row + 1
                Sheets("sheet2").Range("B" & lr).Value = Range("B" & ActiveCell.Row).Value
                Sheets("sheet2").Range("C" & mr).Value = Range("D" & ActiveCell.Row).Value
                Sheets("sheet2").Range("D" & nr).Value = Range("F" & ActiveCell.Row).Value
            End If
        End If
    End Sub