Copy Rows Based On Matching Criteria From One Sheet To Another
There's 2 ways we can go about this.
Code 1
The first is sticking with what you were doing, which may or may not be the slower way of accomplishing this (depending on how many cells you're moving through.)
Option Explicit
Private Sub Workbook_Open()
Dim wsWO As Worksheet: Set wsWO = ThisWorkbook.Sheets("Scheduled WO's")
Dim wsB As Worksheet: Set wsB = ThisWorkbook.Sheets("Branden")
Dim LastRow As Long: LastRow = wsWO.Cells(wsWO.Rows.Count, 1).End(xlUp).Row
Dim i As Long
wsB.Range("A2:Q10000").ClearContents
For i = 2 To LastRow
If wsWO.Cells(i, "G").Value = "Branden" Then _
wsWO.Cells(i, "G").EntireRow.Copy _
wsB.Range("A" & wsB.Cells(ws.Rows.Count, 1).End(xlUp).Row + 1)
Next i
End Sub
Code 2
The other way we can do this is by specifically finding only occurences of "Branden", and copying those rows over.
Option Explicit
Private Sub Workbook_Open()
Dim wsWO As Worksheet: Set wsWO = ThisWorkbook.Sheets("Scheduled WO's")
Dim wsB As Worksheet: Set wsB = ThisWorkbook.Sheets("Branden")
Dim findBranden As Range: Set findBranden = wsWO.Range("G:G") _
.Find(What:="Branden", LookIn:=xlValues, LookAt:=xlWhole)
Dim firstResult As String
wsB.Range("A2:Q10000").ClearContents
If Not findBranden Is Nothing Then
firstResult = findBranden.Address
Do
findBranden.EntireRow.Copy _
wsB.Range("A" & wsB.Cells(wsB.Rows.Count, 1).End(xlUp).Row + 1)
Set findBranden = wsWO.Range("G:G").FindNext(findBranden)
Loop While Not findBranden Is Nothing And findBranden.Address <> firstResult
Else: MsgBox "Nothing to move today.", vbInformation, ""
End If
End Sub
You'll notice there's a couple new things in both codes.
An important one is Option Explicit
. Including this at the top of your code module will alert you at compile if you have any variables that aren't declared. This is incredibly useful because it will catch spelling mistakes and the like before your code runs. I dare say all experienced VBA coders use Option Explicit
or have Require Variable Declaration
turned on in the Tools > Options > Editor menu.
Another very important change was declaring the specific type of variables we are using. In your code, LastRow
and i
are assumed as Variant
types because you never specified their use. It's good practice to be as specific as you can in coding, especially with variable declarations, because it will make troubleshooting your code a lot more simple.
I also declared your worksheets as variables to make the written code smaller, and easier to read.
Literature You May Find Useful
Why Option Explicit
?
Why Require Variable Declaration
?
Why declare the specific type of variable?
Both methods are viable and easy to manipulate. Let me know if I've managed to help :)