Search code examples
excelvba

Copy entire row based on a cell value and paste in another sheet


I am trying to:
Copy an entire row from Sheet1 if cell value in the row is for example >3000.
Paste that row in sheet2.

It gets stuck at EntireRow.EntireRow while I am trying to copy that entire row to sheet2.

Sub deviation()

    Dim DataRg As Range
    Dim blankrng As Range
    Dim cell As Range
    Dim I As Long

    Q = Worksheets("Sheet2").UsedRange.Rows.Count
    P = Worksheets("Sheet1").UsedRange.Rows.Count

    If I = 1 Then
        If Application.WorksheetFunction.CountA(Worksheets("Sheet1").UsedRange) = 0 Then Q = 0
    End If

    Set DataRg = Worksheets("Sheet1").Range("b2:w185" & P)
    Application.ScreenUpdating = False

    If CStr(DataRg(I).Value) >= "3000" Then
        EntireRow.EntireRow
    End If
    
End Sub

Sheet1

a  10   100   4000
b  15   102   2900
c  3000 3010  129

Expected output, as the value in at least one cell is >3000

a  10   100   4000
c  3000 3010  129

Solution

  • I believe the following should help you achieve your expected outcome:

    Sub deviation()
        Dim wb As Workbook: Set wb = ThisWorkbook
        Dim wsCopyFrom As Worksheet: Set wsCopyFrom = wb.Sheets("Sheet1")
        Dim wsPasteTo As Worksheet: Set wsPasteTo = wb.Sheets("Sheet2")
        'above declare and set the relevant worksheets
        Dim LastRowSheet1 As Long, LastRowSheet2 As Long, counter As Long
        'declare variables to verify last rows in both worksheets
    
        LastRowSheet1 = wsCopyFrom.Cells(Rows.Count, 1).End(xlUp).Row
        'get the last row with some data on Column A Sheet1
        NextRowSheet2 = wsPasteTo.Cells(Rows.Count, 1).End(xlUp).Row + 1
        'get the last row with some data on Column A Sheet2 and add 1
        
        For counter = 1 To LastRowSheet1
        'loop throught Rows 1 to Last on Sheet1
            If wsCopyFrom.Cells(counter, 2).Value >= "3000" Or wsCopyFrom.Cells(counter, 3).Value >= "3000" Or wsCopyFrom.Cells(counter, 4).Value >= "3000" Then
            'Check if any value in Column B, C or D have a value greater or equal to 3000
                wsCopyFrom.Rows(counter).EntireRow.Copy wsPasteTo.Range("A" & NextRowSheet2)
                NextRowSheet2 = NextRowSheet2 + 1
            End If
        Next counter
    End Sub