'Excel VBA For Loop (Bottom to Top) assistance
I'm new to creating loops, I can read VBA alright but have a more difficult time writing in the correct syntax. I often get "Object Not Set" errors.
Here is my issue: I have a range of cells where each cell contains a different value (Call this range1) and looks against a template file. I copy all sheets of the template file (3 sheets), these first 2 steps work fine.
I need to loop from the bottom to top and look on all 3 sheets to delete all rows where the value in a column (Call this range2) <> the value in Range1.
I'm anticipating creating 3 loops for this, but the above premise is the same for all loops, just with different ranges. (I know a lastRow code could be used, but I'm not very confident in having the last row be different for 3 sheets with varying row counts)
Here is an example from the first loop I have written, which currently runs Top -> bottom and ends up skipping every other line because it deletes the active row, cells shift up a row, then moves on to the next row. the BrNoRng = Range1 described above
Dim x As Integer
Dim BrNo As String
Dim BrNoRng As Range
Dim c As Range, rng
Set BranchRange = Range("B2:B35") 'this range is in separate file
Set BrNoRng = Range("B2") ' ^^ this range is in separate file
BrNo = BrNoRng.Value
'******Begin Loop 1***************
For x = 1 To 34 'Loop 1 is fine to run top -> bottom
'******Begin Loop 2****************** 'Loop 2 Needs to run Bottom -> Top
Sheets1.Activate 'Not actual name of the sheet, used as a placeholder sheet name,
'this is where the rows need to delete
Set rng = Range("C3:C2500")
For Each c In rng.Rows
If c.Value <> BrNoRng.Value Then
c.Value.EntireRow.Delete
End If
Next c
'*****End loop 2**********
Next x
'*****End Loop 1*************
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
