Question

How do I copy the top 25 rows of filtered data?

Asked by: angelfromabove

I need to add VBA code to an Excel Macro to copy the top 25 rows of top values in "Column H" regardless of what row numbers those top 25 fall in because of  other autofilters I might have on. My data is in Columns A-AF.  The rows vary each week because the data is dynamic.  Each week, I need to select the top 25 rows based on the values in "Column H" and a filtered selection in "Column A".  I then need to copy the entire unhidden 25 rows.  If I can just get it to select the Top 25 "relatively" in the Macro every time, I can handle the pasting part later.  The "Top 10" function does not work with multiple filters, it always return fewer rows than 25.  I also need to copy my Header Rows in Row 1. I tried recording with a relative reference and it still doesn't work, it always refers to an absolute cell reference when I select the range to copy.  Can Excel determine the top 25 rows in a filter based on the criteria in "Column H"?  Help!!!!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-26 at 18:41:34ID24845850
Tags

Microsoft Excel 2003

,

2007

Topics

Microsoft Excel Spreadsheet Software

,

Microsoft Visual Interdev

,

Microsoft IIS Web Server

Participating Experts
4
Points
500
Comments
27

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Excel macro to hide a row based on cell value in row
    Have a user who needs to write a macro to hide an entire row if a specific cell in the row equals zero. Sounds simple, but can't quite get the if...then set up properly. Any ideas? TIA, Gromit
  2. macro to filter date range
    I require a macro to filter a certain date range (in a column) then sum up the qty field next to it (in another column). I have written this for the date range: Selection.AutoFilter Field:=1, Criteria1:="=" & InputBox("DATE FROM"), Operator:=xlOr, _ Cr...
  3. A Macro or VBA Code to hides all rows where A2-501…
    Hi Is it possible to write a Macro or VBA code which looks at the contents of the cells in column A2-A501 and hides all the rows which have a 0 in cell A? Cell A will be from a link, i.e. =Sheet2 etc Many thanks David
  4. macro to copy formula in cell to all rows
    Hi, I have a need to copy a formula from a particular cell to all cells in that column. The number of rows vary. e.g. If I have sheet with 20 rows, copy formula in b3 to b4 through b20. If I have sheet with 2000 rows, copy formula in b3 to b4 through b2000. Probably about...
  5. Filtering with VBA
    I would like to copy and paste a list of cell values into a new worksheet after filtering the list based on values in another column in VBA. How to do it? Thanks, MV

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: EoDawgPosted on 2009-10-26 at 19:33:51ID: 25668748

I would use the copy visible option to paste into a sheet temporarily, then take the top 25 from that list, because at that point it's just regular, unfiltered data.

 

by: angelfromabovePosted on 2009-10-26 at 19:44:46ID: 25668780

Thank you so much for your quick response, but there must be a way to do it with filters.  This portion is only a smaller part of a larger macro and I don't want to have to edit it to add a temporary sheet, and then add code to delete the sheet later, etc.

What do you think, is this as good as it gets?

 

by: EoDawgPosted on 2009-10-26 at 19:53:32ID: 25668810

just to elaborate on recording the macro,

assuming your data is in sheet 1 and you've sheet 2 and 3 present also
when you have your filtered data
Edit, goto, special, Choose "visible cells only"
In sheet2 paste the data (which will have the header)
sort in descending order the column you want the top25 from
copy rows 1 - 26 (header + top25)
paste into sheet3, which is your result.

I had done this on a mock up which is attached. you can filter by a, b, c, d with over 25 results for each. sheet3 will only have the top25.

 

by: brettdjPosted on 2009-10-26 at 19:57:48ID: 25668832

You can autofilter the top 25 items in H - see below

Cheers

Dave

Columns("H").AutoFilter Field:=1, Criteria1:="25", Operator:=xlTop10Items

                                              
1:

Select allOpen in new window

 

by: EoDawgPosted on 2009-10-26 at 19:59:19ID: 25668836

sorry I was mid mock up there.

The overhead of using a temp sheet outweighs trying to keep it all within the filtering, as you can see there's not that much code in the macro as it's using alot of built in functions (copy visible, sorting descending, then copy and pasting again).

I rarely use filters so there might be a very straight forward answer. But that's my stab at it ;)

Off to bed now incase you're wondering about the "radio silence" for the next few hours from my side.

 

by: EoDawgPosted on 2009-10-26 at 20:00:19ID: 25668844

Brett to the rescue :) o//

 

by: angelfromabovePosted on 2009-10-26 at 20:11:07ID: 25668872

Thank you Brett! But keep in mind, I'm also filtering it for a value in Column A as well, and how would I tell the Macro to copy the top 25 items every time, without picking up all of the hidden rows?

 

by: angelfromabovePosted on 2009-10-26 at 20:14:26ID: 25668887

This is what I have so far, I'm sooo close but it only copies the top  25 hidden rows for some reason:
Range("A1").Select
    Selection.AutoFilter Field:=1, Criteria1:="Small Business (SB - IL/IN)"
    Selection.SpecialCells (xlCellTypeVisible)
    ActiveCell.Offset(1, 0).Rows("1:25").EntireRow.Select
    Selection.Copy
    ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
    ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
    ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    ActiveWindow.ScrollWorkbookTabs Sheets:=1
    Sheets("SB - Top 25 - IL&IN").Select
    Range("A1").Select
    Selection.End(xlUp).Select
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    ActiveCell.Offset(5, 0).Range("A1").Select
    ActiveSheet.Paste
End Sub

 

by: angelfromabovePosted on 2009-10-26 at 20:31:33ID: 25668942

And thank you again, but can you tell me where would the Auto Filter of Column H fit into the macro I have so far, and can you tell me what I've done wrong based on what I posted above??

 

by: angelfromabovePosted on 2009-10-26 at 20:35:03ID: 25668957

Oh and sorry, one last comment before I go to sleep, When I try the Top 25 feature to Auto Filter  Column H , (not in a macro) It only gives me 17 visible rows, not 25. I think it's because I already have another filter in Column A.  And Yes there are definitely more than 17 rows that fit my criteria.

 

by: angelfromabovePosted on 2009-10-26 at 20:40:22ID: 25668981

I hit the wrong button, please keep the solutuions coming, I didn't mean to close it.

 

by: brettdjPosted on 2009-10-26 at 22:28:34ID: 25669346

> When I try the Top 25 feature to Auto Filter  Column H , (not in a macro) It only gives me 17 visible rows, not 25.  I think it's because I already have another filter in Column A

I think that VBA a copy of the sheet to a (hidden) working sheet and then  processing it is the way to go. It's minor coding wise

Do you want us to proceed that way?

Cheers

Dave

 

by: roryaPosted on 2009-10-27 at 02:38:06ID: 25670484

You could try something like this:

Sub FilterAndCopy25()
   Dim wksSource As Worksheet, wksDest As Worksheet
   Dim strFilter1 As String, strFilter2 As String
   Dim rngFirstCell As Range, rngLastCell As Range, rngData As Range, rngCell As Range
   Dim lngCounter As Long, lngStop As Long
   
   ' sheet to copy from
   Set wksSource = ActiveSheet
   ' sheet to copy to
   Set wksDest = Sheets("Target")
   
'   strFilter1 = "Small Business (SB - IL/IN)"
   ' column A filter
   strFilter1 = "1"
   ' column H filter
   strFilter2 = "a"
   
   With wksSource
      With .Range("A1").CurrentRegion
         .AutoFilter field:=1, Criteria1:=strFilter1
         .AutoFilter field:=8, Criteria1:=strFilter2
      End With
      Set rngData = .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
      lngStop = Application.Min(rngData.Count, 25)
      ' check there's data to copy!
      If lngStop > 1 Then
         For Each rngCell In rngData
            If lngCounter = 1 Then
               Set rngFirstCell = rngCell
            ElseIf lngCounter = lngStop Then
               Set rngLastCell = rngCell
               Exit For
            End If
            lngCounter = lngCounter + 1
         Next rngCell
         ' copy data
         .Range(rngFirstCell, rngLastCell).SpecialCells(xlCellTypeVisible).EntireRow.Copy
         wksDest.Cells(.Rows.Count, "A").End(xlUp).Offset(5, 0).PasteSpecial
         Application.CutCopyMode = False
      End If
   End With
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

Select allOpen in new window

 

by: roryaPosted on 2009-10-27 at 02:39:04ID: 25670492

Hmm, just re-read the question - is it the top 25 rows by value, or just the top 25 rows by position? (mine does the latter)

 

by: krishnakrkcPosted on 2009-10-27 at 04:46:56ID: 25671237

Hi,

try

Kris

Sub kTest()
Dim fRng As Range, tmpSht   As Worksheet, ws As Worksheet
Dim DestSht As Worksheet, Crit, Top25 As Range
 
Crit = "Small Business (SB - IL/IN)"
Set ws = ActiveSheet
Set DestSht = Sheets("SB - Top 25 - IL&IN")
 
With Application
    .ScreenUpdating = 0
    .DisplayAlerts = 0
End With
With ws.UsedRange
    .AutoFilter Field:=1, Criteria1:=Crit
    Set fRng = .SpecialCells(xlCellTypeVisible)
End With
    Set tmpSht = Sheets.Add
    fRng.Copy: tmpSht.Range("a1").PasteSpecial xlPasteValues
    With tmpSht.UsedRange
        .Sort .Cells(2, "h"), xlDescending
        Set Top25 = .Cells(1).Resize(26, .Columns.Count)
    End With
    Top25.Copy DestSht.Range("a" & Rows.Count).End(xlUp).Offset(1)
    tmpSht.Delete
With Application
    .ScreenUpdating = 1
    .DisplayAlerts = 1
    .CutCopyMode = 0
End With
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

Select allOpen in new window

 

by: angelfromabovePosted on 2009-10-27 at 07:23:40ID: 25672734

Hi Rorya, It's the top 25 by Value.  Thanks so much!

Thanks to you Kris as well! I will try them both shortly.

 

by: roryaPosted on 2009-10-27 at 07:28:16ID: 25672774

In that case, mine won't work. I would use an advanced filter instead if you can?

A sample workbook would be useful here. :)

 

by: angelfromabovePosted on 2009-10-27 at 09:39:44ID: 25674511

Rorya, Kris:

Per your request, attached is a sample workbook!

Cheers!

 

by: angelfromabovePosted on 2009-10-27 at 09:48:18ID: 25674606

Hi Kris, I just gave your VBA code a try, and it ran, but it only returned 15 rows???

 

by: angelfromabovePosted on 2009-10-27 at 09:51:46ID: 25674649

Actually, it was 14 rows, and not only that, it only pasted through column "H", I needed the entire  row copied and pasted through Column "AF".

Cheers!

 

by: angelfromabovePosted on 2009-10-27 at 09:57:06ID: 25674713

Brett DJ,

In the interim, can we try the VBA Code to paste to a hidden sheet? Would you be able to write that for me?

Cheers!

 

by: angelfromabovePosted on 2009-10-27 at 10:10:47ID: 25674885

Hang on Kris, I just ran it again, because in my sample workbook, there were some cells in Column A that were "#N/A, and when I replaced them with a value, I think it worked, let me test again but you may be my hero and go to the top of the Genius List, because this stumped several very intelligent people!

 

by: krishnakrkcPosted on 2009-10-27 at 10:12:53ID: 25674906

Try

Sub kTest()
Dim fRng As Range, tmpSht   As Worksheet, ws As Worksheet
Dim DestSht As Worksheet, Crit, Top25, SortCol As Long
Dim k(), i As Long, n As Long, Hdr, x, c As Long
 
Crit = "Small Business (SB - IL/IN)"
 
Set ws = Sheets("Detail-IL IN")
Set DestSht = Sheets("SB - Top 25 - IL&IN")
Hdr = DestSht.Range("a4:n4")
With Application
    .ScreenUpdating = 0
    .DisplayAlerts = 0
End With
With ws.UsedRange
    .AutoFilter Field:=1, Criteria1:=Crit
    Set fRng = .SpecialCells(xlCellTypeVisible)
End With
    Set tmpSht = Sheets.Add
    fRng.Copy: tmpSht.Range("a1").PasteSpecial xlPasteValues
    With tmpSht.UsedRange
        SortCol = .Rows(1).Find("Principal Bal", lookat:=xlWhole).Column
        .Sort .Cells(2, SortCol), xlDescending
        Top25 = .Cells(1, 2).Resize(26, .Columns.Count - 1)
    End With
    ReDim k(1 To 25, 1 To 14)
    For i = 2 To UBound(Top25, 1)
        If Len(Top25(i, 1)) Then
            n = n + 1
            For c = 1 To UBound(Top25, 2)
                x = Application.Match(Top25(1, c), Hdr, 0)
                If Not IsError(x) Then k(n, x) = Top25(i, c)
            Next
        End If
    Next
    With DestSht.Range("a" & Rows.Count).End(xlUp).Offset(1)
        .Resize(n, 14).Value = k
    End With
    tmpSht.Delete
    ws.AutoFilterMode = False
With Application
    .ScreenUpdating = 1
    .DisplayAlerts = 1
    .CutCopyMode = 0
End With
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:

Select allOpen in new window

 

by: angelfromabovePosted on 2009-10-27 at 10:38:38ID: 25675185

Thanks Kris,  Actually they both work, except the 2nd one cuts off the Header Row, can you add that back in?  I am going to accept both your solutions! You are the very best, Thank You.

 

by: angelfromabovePosted on 2009-10-27 at 10:43:50ID: 31646242

This was quite a challenge and this solution from Kris rose to the challenge.  I am so very grateful to you for taking the time out to help a novice like me!

 

by: angelfromabovePosted on 2009-10-27 at 10:45:13ID: 25675276

Kris, This is closed, but as I mentioned above the Header Row wasn't coming through, how can I fix that?
Thanks!

 

by: krishnakrkcPosted on 2009-10-27 at 18:49:06ID: 25679371

Hi,

Here you go.. some tweak in the following part

Kris


With DestSht.Range("a" & Rows.Count).End(xlUp).Offset(1)
    .Resize(, UBound(Hdr, 2)).Value = Hdr 'New line for Header row
    .Offset(1).Resize(n, 14).Value = k 'modified this line
End With
                                              
1:
2:
3:
4:
5:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...