Very novice, trying to write a VBA code in EXcel 2010 to select filter value from a drop down list located in cell A1 of Sheet1 and apply filter value on column 4 of a data range A7:S1000 located on Sheet2. Below is the code, inserted in Sheet1, that I am using, but returning nothing. Where am I getting it wrong? Thanks aa lot.
Private Sub Worksheet_Change(ByVal Target As Range)
' Cell with dropdown where value to be selected
Const DropDown = "a1"
' Sheet with data range to apply filter
Const TableSheet = "Sheet2"
' Top left cell of the data range
Const TableRange = "a7"
If Not Intersect(Range(DropDown), Target) Is Nothing Then
Application.EnableEvents = False
If Range(DropDown).Value = "" Then
Worksheets(TableSheet).ShowAllData
Else
Worksheets(TableSheet).Range(TableRange).AutoFilter _
Field:=4, Criteria1:=Range(DropDown).Value
End If
Application.EnableEvents = True
End If End Sub
@Scottyfrog I was hoping the advice I offered above in the comments would do the trick, but unfortunately it didn't. As an alternative, I rewrote your code in a way that was simpler for me to understand. I tested it on my own computer & it seems to work OK.
In addition, a possible cause of your problem could be that the filter couldn't find any values that matched your criteria. I've added a test to your code that will tell you if it can't find any values that match.
Let me know how it goes, and if it works, please uptick the answer.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Range("A1"), Target) Is Nothing Then
If Range("A1").Value = "" Then
Worksheets("Sheet2").ShowAllData
Else
If Application.WorksheetFunction.CountIf(Worksheets("Sheet2").Range("D:D"), Range("A1")) = 0 Then
MsgBox "The Filtered value doesn't exist in column D on sheet 2"
Exit Sub
End If
Worksheets("Sheet2").Range("A7:S7").AutoFilter Field:=4, Criteria1:=Range("A1").Value
End If
End If
End Sub
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.