loop through autofilter drop down

jacknc

Board Regular
Joined
Nov 28, 2005
Messages
75
Office Version
  1. 365
  2. 2019
I currently have a macro that i run after first selecting a state from autofilter list. I would like to create a loop that takes first line AFTER custom... on autofilter list and runs macro. Then goes to next item in autofilter list. Currently the 'dropdown' is located on sheet 4 a1

Any help would be greatly appreciated.

Thanks,
Jack
 
Hi, I got the file you sent.

I figured out why "Kansas" was being skipped--it's already being found in the list as "Arkansas." Something that I should have already realized anyway, but oh well, not much to do about it now.

Anyhoo.

In the TextExists function, change this
Code:
x = WorksheetFunction.Search(currText, Criteria)
to this
Code:
x = WorksheetFunction.Find(currText, Criteria)

We're changing it to use the FIND function instead of SEARCH. Both functions basically do the same thing, but the FIND function is case-sensitive. As long as you have "Kansas" and "Arkansas" listed just as they are now, it should see them separately and give you 50 files, not 49.
 
Upvote 0

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
Kansas loves you!!!!!!!!!!!!!!!!!!!
Thank you.
One other question about this:

Wonder if I have cell with: San Johns and and another called San Johnson am I going to have the same problem?
Maybe I should put some sort of delimiter to the cells?

Thanks again,
Jack
 
Upvote 0
Oh, shoot. I forgot you wanted to do it on the counties, too. I'll play with it some more, see if I can come up with anything. Don't know if I'll get it today, though :confused:
 
Upvote 0
I think I may have it, now--something I should have thought of in the first place, really :rolleyes: :oops:

This will use the advanced filter on the column to find unique values. So only 1 instance of each item will be displayed. Then just set the visible cells as a range, and you can loop through that range as the criteria instead of using the array and TextExists function. Shouldn't have to worry about any "Kansas"-like scenarios, at any rate :)

Code:
Dim Criteria As Range, myRng As Range

Sub test()
Dim cell As Range

Application.ScreenUpdating = False

With Sheets("Sheet3")
    'turns off autofilter if it is on
    If .AutoFilterMode = True Then .AutoFilterMode = False
    
    'range of data, not including header row (data starts in row 2)
    Set myRng = .Range("A2", .Range("A65536").End(xlUp))
    
    'filter column A to show unique items (1 instance of each entry)
    .Columns("A:A").AdvancedFilter Action:=xlFilterInPlace, Unique:=True
    
    'set filtered results as range
    Set Criteria = myRng.SpecialCells(xlCellTypeVisible)
    
    'remove filter
    ActiveSheet.ShowAllData
    
    With .Rows("1:1")
        .AutoFilter 'turn on autofilter
        For Each cell In Criteria
            'filter column A using criteria
            .AutoFilter field:=1, Criteria1:=cell.Value
                        
            'call the Export macro
            Sheets("Sheet1").Range("A2:B600").ClearContents
            Call Export
         Next cell 'display filter results for next item
    
        .AutoFilter  'turn off autofilter
    End With
End With

Application.ScreenUpdating = True

End Sub

Sub Export()
Dim Textfile As Variant
Dim XportArea As Range, Cel As Range
Dim i As Long, iCol As Long, iRow As Long
Dim LastRow As Long, iFnum As Integer, x As Integer
Dim Path As String, FileName As String
Dim SaveFile As String, ShName As Variant

'copy visible cells in columns A:B of sheet 3 (filtered results)
myRng.SpecialCells(xlCellTypeVisible).Copy

'paste to Sheet1
Sheets("Sheet1").Range("A2").PasteSpecial xlPasteValues
    
Path = "C:\test\"
Textfile = Sheets("Sheet1").Range("A2").Value
FileName = LCase(Replace(Textfile, " ", ""))
SaveFile = Path & FileName & ".txt"

If Textfile = False Then Exit Sub

On Error Resume Next
'open / create the textfile
iFnum = FreeFile

Open CStr(SaveFile) For Append As iFnum

'since you're performing the same thing these sheets, _
you can turn this into a loop
ShName = Array("Output#1", "Output#2", "Output#3", "Output#4", "Output#5")

For x = LBound(ShName) To UBound(ShName)
    If ShName(x) = "Output#4" Then
        ' Get number of columns value from sheet 1
        i = Sheets("Sheet1").Range("C2").Value
        Set XportArea = Sheets(ShName(x)).Range("B1").Resize(5, i)
    Else
        'Select the cells to export:
        With Sheets(ShName(x))
        .Activate
        
            Set XportArea = .Range([a1], .[A65536].End(xlUp))
        End With
    End If
    For iCol = 1 To XportArea.Columns.Count
        For iRow = 1 To XportArea.Rows.Count
            If XportArea.Cells(iRow, iCol).Text <> "" Then
                Print #iFnum, XportArea.Cells(iRow, iCol).Text
                Debug.Print XportArea.Cells(iRow, iCol).Text
            End If
        Next iRow
    Next iCol
Next x

Close #iFnum

End Sub

I believe this should also work for the counties--I wasn't exactly sure how you were planning to go about filtering those (since it is possible for multiple states to have counties with the same name), so I haven't bothered with that, yet. This should just do the states.
 
Upvote 0
Kristy,
Again I would like to extend my gratitude towards yourself and this board. I have learned quite a bit from these exchanges - saved and lost a few hairs in the process. :) I studied you latest routine and believe I can get the counties to work as I was able to with your last routine.

The whole bases of the array was so that I can filter the states - copy BOTH state and county over to 'Sheet1' recently changed to Master - since thats where the guts of everything begins. I can run routine for each state by this or if needed can run another loop inside of current one to deal with the pasted states/counties.

The latest code works great with creating unqiue names. But when it gets ready to copy it only copies the filtered list from A col. This should copy A:B filtered. I have played a little with it this morning. Am I right that another rng needs to be set?

Thank you so much for the time and teachings that you have done thus far. I really appreciate it.

Thanks,
Jack
 
Upvote 0
Oop! My fault, sorry. :oops:

I changed the myRng while I was testing things yesterday and apparently forgot to change it back.

Where this line is referring to A65536, change it to B65536 instead.
Code:
Set myRng = .Range("A2", .Range("A65536").End(xlUp))
 
Upvote 0
I got it! Your code worked perfect except for the copy portion(I needed 2 column copied) Changing the myrng didnt work because thats where the criteria is set. I left your code as is with following line replaced:

myRng.SpecialCells(xlCellTypeVisible).Copy

Sheets("Sheet3").Range("A2", .Range("B65536").End(xlUp)).SpecialCells(xlCellTypeVisible).Copy

this works good. I appreciate your quick response again. You are awesome!
 
Upvote 0
Kristy,

I wanted to thank you for all of your help. My project is up and running. I wanted to ask you one last question.

Currently I have several macros all based on the export function. All of them use the first sub routine listed below.
Code:
Sub Counties()
Dim StateCell As Range
With Sheets("Sheet3")
.Activate
If .AutoFilterMode = True Then .AutoFilterMode = False
Set AFilterRng = .Range("A2", .Range("A65536").End(xlUp))
.Columns("A:A").AdvancedFilter Action:=xlFilterInPlace, Unique:=True
Set AFCriteria = AFilterRng.SpecialCells(xlCellTypeVisible)
ActiveSheet.ShowAllData
With .Rows("1:1")
.AutoFilter
For Each StateCell In AFCriteria
.AutoFilter field:=1, Criteria1:=StateCell.Value
Sheets("Master").Range("A2:B600").ClearContents
Sheets("Sheet3").Range("A2", .Range("B65536").End(xlUp)).SpecialCells(xlCellTypeVisible).Copy
Sheets("Master").Range("A2").PasteSpecial xlPasteValues
Call CountiesExport   ' <----------------****This changes****
Next StateCell
.AutoFilter
End With
End With
Application.ScreenUpdating = True
Sheets("Master").Activate
End Sub

Even though the project works fine I am thinking about condening the subs. As I mentioned I currently have 9 subs exactly like the one above with only one line changed - the call portion. If you were me would you make this a seperate routine or keep them as is? Just wanted to get your expert opinion.

Thanks,
Jack
 
Upvote 0
Well, I wouldn't call my opinion on anything "expert" by a long shot. No way :)

However, if I had the same setup as you are currently describing, I would probably try to find a way to loop it or something so you didn't have to have all of the different subs that do the exact same thing.
 
Upvote 0

Forum statistics

Threads
1,215,537
Messages
6,125,389
Members
449,222
Latest member
taner zz

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