Autofilter works in macro but not as a UDF

excel.vba

New Member
Joined
May 26, 2011
Messages
30
I have created a function which identifies the column of the country. Once identified it filters based on the string "W" and the month range. After which it is supposed to return number of rows remaining. The filtering occurs in another worksheet called "SUMMARY". But the function is called in a worksheet "INPUT". This works perfectly fine as a macro but not as a UDF. As a UDF, it doesnt filter but instead all the used rows in the "SUMMARY" worksheet. Let me know if there is a need for further clarification. Thanks!!

UDF Code

Code:
Public Function WorkingDays(StartDate As Date, Enddate As Date, Country As String) As Integer

SDate = CLng(StartDate)

EDate = CLng(Enddate)

Sheets("SUMMARY").Select
CtryColumn = Application.WorksheetFunction.Match(Country, _ Sheets("SUMMARY").Range("A4:Z4"), 0)


With Sheets("SUMMARY")
    
 Selection.AutoFilter Field:=2, Criteria1:=">=" & SDate, Operator:=xlAnd _
    , Criteria2:="<=" & EDate
    
 Selection.AutoFilter Field:=CtryColumn, Criteria1:="W"

End With
For Each Rng In Sheets("SUMMARY").UsedRange.SpecialCells(xlVisible).Areas
        x = x + Rng.Rows.Count
        
    Next Rng


WorkingDays = x - 4

End Function
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
UDF can't do modificatons - no sorting, no filtering, no changing values etc. Subs and Functions called from UDF are under same restrictions as UDF.
 
Upvote 0
You can use Sub instead, but this will be more work to do. You will have to ask for input data with InputBox function. :)
 
Upvote 0

Forum statistics

Threads
1,224,534
Messages
6,179,391
Members
452,909
Latest member
VickiS

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