简体   繁体   中英

Dynamic Excel VBA filter

I have one macro which filters raw data according to fix criteria. I have assigned this macro on one button (Move In).

在此处输入图片说明

this macro is showing the details raw data for cell D11 (41 value) code is like

Sub Jan_in()
Application.ScreenUpdating = False
Dim sStradd As String
Sheets("Hiring_Attrition").Activate
Range("A3").Select
sStradd = ActiveCell.CurrentRegion.Address
ActiveSheet.Range(sStradd).AutoFilter Field:=1, Criteria1:="Jan-17"
Call clear
Sheets("Hiring_Attrition").Activate
ActiveSheet.Range("B3:H3").Select
Sheets("Hiring_Attrition").Range(Selection, Selection.End(xlDown)).Select
Selection.Copy Sheets("Report").Range("B8")
Selection.AutoFilter
Sheets("Report").Activate
Sheets("Report").Range("B:H").EntireColumn.AutoFit
Sheets("Report").Range("A1").Select
Application.ScreenUpdating = True
End Sub `

I have multiple macros like this but now I want a macro which pick filter according to cell reference. Like Macro will take criteria one as -2 row of same column for which selected cell is and criteria two -2 column of same row for which selected cell.

Let me know if any further clarification is need.

Dynamic Filter:

I have a sheet with a drop down selector (which I built by this instruction: http://www.techrepublic.com/blog/microsoft-office/how-to-add-a-drop-down-list-to-an-excel-cell/ ). Filter can be modified based on which item is selected. Code looks like this:

For i = 1 To 10
If Range("SELECTOR").Value = Sheets("sheet2").Range("a" & i).Value Then
    Selected = i
End If
Next

The above code identifies which value from the list is selected. "SELECTOR" is the drop down cell, and we're stepping through 10 cells on the second sheet to determine which row number was selected. Now, you can use that info to customize your filter. For example:

If Selected = 7 Then
 Range("A4:Z1000").AutoFilter
 Range("A4:Z1000").AutoFilter field:=1, Criteria1:="", visibledropdown:=True
Else
 Range("A4:Z1000").AutoFilter
 Range("A4:Z1000").AutoFilter field:=Selected + 1, Criteria1:="x", 
 visibledropdown:=True
End If

The reason I do the empty AutoFilter first, is because it clears the previous filter. Criteria = "x" because that's what I was filtering by, but you could sub in a variable to make it dynamic.

Hope this helps.

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