Search code examples
excelvbacopy-paste

Issue with setting TargetCell in macro copy paste


I am new on this forum and seek some help with a macro. I have two worksheets: one where data are input ("DataEntry") and the other where data are stored ("DataSheet"). The whole idea is that a user can add as many data (s)he wants in the DataEntry worksheet and that all the entries are listed in successive order starting DataSheet!F10 and then move on F11, F12, etc. I have already used some codes from this forum to do the whole copy paste thing but for some reasons cannot set the TargetCell on F10. All these entries should have a light yellow font and be numbered starting with 1 in E10, 2 in E11, etc.

Looking forward reading your solutions! Thanks

Here is the coding:

Sub ConstrProgramme_addition()

    Dim DataEntry As Worksheet, DataSht As Worksheet
    Dim ItemName As Range, ItemCount As Range
    Dim NRow As Long, TargetCell As Range

    With ThisWorkbook
        Set DataEntry = .Sheets("DataEntry")
        Set DataSht = .Sheets("Datasheet")
    End With

    With DataEntry
        Set ItemName = .Range("C4")
        Set ItemCount = .Range("E4")
    End With

    With DataSht
        
        If IsEmpty(Range("F10")) = True Then
        Set TargetCell = .Range("F10")
        Else
        Set TargetCell = ActiveCell.Offset(NRow, 0).Select
    
        
        NRow = .Range("F" & Rows.Count).End(xlUp).Row + 1
        
        End If
        
        TargetCell.Resize(ItemCount.Value, 1).Value = ItemName.Value
    End With

End Sub

Solution

  • You can shorten it a little:

    Sub ConstrProgramme_addition()
    
        Dim DataEntry As Worksheet, TargetCell As Range
    
        Set DataEntry = ThisWorkbook.Sheets("DataEntry")
        
        With ThisWorkbook.Sheets("Datasheet")
            Set TargetCell = .Cells(.Rows.Count, "F").End(xlUp).Offset(1, 0)
            If TargetCell.Row < 10 Then Set TargetCell = .Range("F10")
            TargetCell.Resize(DataEntry.Range("E4").Value, 1).Value = DataEntry.Range("C4").Value
        End With
    
    End Sub