简体   繁体   中英

Filter based on multiple cell values in separate sheet then loop through results

Ok,

Hopefully this isn't too convoluted. I'm trying to filter a large number of transactions based on customer ID number. I have a list of about 60 important customers I need to track in a separate sheet. It has their customer ID number and then their name and other data. So everyday I'm taking about 20,000 transactions and filtering them manually. Then going through and copying and pasting the first instance of each transaction for the day into another sheet.

So Far this is what I have:

Dim Arr() AS Variant 
Arr = Sheet2.range(“A1:A60”)
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
ActiveSheet.Range(“A1:A” & LastRow).AutoFilter Field:=1,_
Criterial:=Arr, Operator:=xlFilterValues

Dim r As Long, endRow As Long, pasteRowIndex As Long

pasteRowIndex = 1

For r = 1 To LastRow

If Cells(r, Columns("A").Column).Value <> Cells(r + 1, Columns("A").Column).Value 
Then Rows(r).Select
Selection.Copy
Sheets("Sheet3").Select
Rows(pasteRowIndex).Select
ActiveSheet.Paste
pasteRowIndex = pasteRowIndex + 1
Sheets("Sheet1").Select
End If
Next r 

As of now it's untested because I'm on vacation. Does this code look proper? If not, what can I do better?

Thanks

A few notes:

  • Change Columns("A").Column to just 1, there is no need to have it like that since you aren't checking other columns.

  • For LastRow it may be easier to simply use Cells(1,1).End(xlDown).Row

  • From what I can see your if command is checking the cell after for the same ID number. This would imply that the last transaction from that ID number is the only one being passed. If you have headings the first row then you could use

    If Cells(r, Columns("A").Column).Value <> Cells(r - 1 1, Columns("A").Column).Value

and start with r = 2

  • Also it seems as though when you are filtering you are only filtering the A column. Change to the following and it should work

    LastCol = Cells(1,1).End(xlToRight).Column

    ActiveSheet.Range(Cells(1,1),Cells(LastRow,LastCol)).AutoFilter Field:=1,_

    Criterial:=Arr, Operator:=xlFilterValues

  • For code simplicity you can also use Dim r, endRow, pasteRowIndex As Long and do not forget to define Dim LastRow as Integer and similar for LastCol if you decide to use it.

If there are still any issues with this when you return please feel free to let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM