Avatar of mcnuttlaw
mcnuttlaw
Flag for United States of America asked on

VBA copy rows with certain values

I would like to copy only certain rows to a new worksheet in the same workbook using VBA.

Copy Row 1 - header row

Copy each row whose "On Hand" number equals 1.

See attached sample worksheet.

ScreenshotBook1.xls
Microsoft Excel

Avatar of undefined
Last Comment
dlmille

8/22/2022 - Mon
dlmille

Option Explicit

Sub copyOnHand()
Dim wkb As Workbook
Dim wks As Worksheet
Dim wksNew As Worksheet
Dim rngOut As Range
Dim rng As Range
Dim r As Range
Dim i As Long

    Set wkb = ThisWorkbook
    Set wks = wkb.ActiveSheet
    
    Set rng = wks.Range("A2", wks.Range("A" & wks.Rows.Count).End(xlUp))
    
    Set wksNew = wkb.Worksheets.Add(after:=wkb.Worksheets(wkb.Worksheets.Count))
    
    wksNew.Range("A1").Resize(, 3).Value = wks.Range("A1:C1").Value
    
    Set rngOut = wksNew.Range("A2:C2")
    
    For Each r In rng
        If r.Offset(0, 2).Value > 0 Then
            rngOut.Offset(i).Value = r.Resize(, 3).Value
            i = i + 1
        End If
    Next r
            
End Sub

Open in new window


See attached.

Dave
Book1.xls
mcnuttlaw

ASKER
Oops.  I forgot to mention that the new worksheet is actually an existing one titled "End Result".

Pressing the button should replace the existing contents of "End Result".
ASKER CERTIFIED SOLUTION
dlmille

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy