[英]VBA code to select filter value from drop down menu on one sheet and apply filter in a table on another worksheet - Excel 2010
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. 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.下面是插入到 Sheet1 中的代码,我正在使用它,但没有返回任何内容。 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. @Scottyfrog 我希望我在上面的评论中提供的建议可以解决问题,但不幸的是它没有。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.