Copy only rows with a match

HalfAce

MrExcel MVP
Joined
Apr 6, 2003
Messages
9,456
OK, let me see if I can describe my problem.
I'm trying to copy from sheet 1 to sheet 2.
In Col.B I have dates (from B2 to B613)
In Col.C I have times (same rows)

What I'm trying to do is loop through the range (B13:B613) and if the date is = to the date above it, or to the last date in sheet 2, copy the date to sheet 2.

This doesn't seem like it should be hard but I can't seem to get it right. :oops:

I've tried (among others) the routine below.
Code:
Sub CopyMatches()
Dim a, a1 As Range
Set a = Sheets("Sheet2").Range("B65536").End(xlUp)
Set a1 = a.Offset(1)

For i = 613 To 2 Step -1
If Cells(i, 2) = Cells(i, 2).Offset(-1) Or Cells(i, 2) = a Then
Cells(i, 2).Copy a1
End If
Next i
End Sub

It copies only the last matching date to sheet 2. (Ignores any matches before the last one, and it doesn't copy the consecutively matching dates...only one instance of it.
I can't see why it shouldn't work. Can anyone else see what I'm missing?

Thanks,
Dan
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
Hi Dan,

Code:
Sub CopyMatches() 
Dim a, a1 As Range 

For i = 613 To 2 Step -1 
  Set a = Sheets("Sheet2").Range("B65536").End(xlUp) 
  Set a1 = a.Offset(1) 
  If Cells(i, 2) = Cells(i-1, 2) Or Cells(i, 2) = a Then 
    Cells(i, 2).Copy a1 
  End If 
Next i 
End Sub

Untested, but the above tries to address 2 issues:
(1) an easier way to refer to the offset, using i-1
(2) the main one: you need to keep re-setting a as you copy data across, so I put it insode the loop.

HTH
Denis
 
Upvote 0
Hi Denis,
I'll keep the "i-1" bit in mind. (Cool.)
I never thought of having to reset a inside the loop. Good eye!
This works beautifully now.
Thank you much.
(y)
Dan
 
Upvote 0

Forum statistics

Threads
1,214,787
Messages
6,121,569
Members
449,038
Latest member
Guest1337

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top