第一篇文章!大家好:)
希望通过VBA /自动过滤器获得一些帮助。我正在创建执行以下操作的筛选工具-
1)用户使用下拉列表和数字输入的组合将一堆参数输入到“ ScreenerOptions”选项卡中2)在“ ScreenerOptions”中的选择驱动VBA代码以自动过滤表,该表位于单独的选项卡“ Master1”中
我希望参数动态链接到单元格,因此下拉菜单中选择的任何选项都会驱动自动过滤器。除了运算符外,我还具有所有动态链接的内容(例如xlFilterValues,xlTop10Percent等)。
下面是我的筛选器中参数的子集。
这里是有效的代码:
Sub Test()
With Sheets("Master1")
'FCF Yield, row 14 in screener - if the user leaves the field blank
If Worksheets("ScreenerOptions").Cells(14, 5) = "" Then
'Then all rows in the table are displayed for this column
'Column6 in the screener is pulling in the relevant
'column number in the table based on MATCH formula
Worksheets("Master1").Range("A4").AutoFilter Field:=Sheets("ScreenerOptions").Cells(14, 6)
'If a parameter is entered, filter is applied
'Criteria reference based on inputs in Screener Options Columns C (3) and E (5)
Else
'Formula in screener tool column 8 tells you if dropdown uses a value operator
'e.g. ">", "=" returns 0
'dropdowns containing text 'percent' return a 1
'If 0 is returned, use operator xlOr to return numberical values and blanks
If Worksheets("ScreenerOptions").Cells(14, 8).Value = 0 Then
Worksheets("Master1").Range("A4").AutoFilter _
Field:=Sheets("ScreenerOptions").Cells(14, 6), _
Criteria1:=Sheets("ScreenerOptions").Cells(14, 3).Value & _
Worksheets("ScreenerOptions").Cells(14, 5).Value, _
Operator:=xlOr, Criteria2:=""
Else
'If 1 is returned, use operators xlTop10Percent, xlBottom10Percent as selected
Worksheets("Master1").Range("A4").AutoFilter _
Field:=Sheets("ScreenerOptions").Cells(14, 6), _
Criteria1:=Worksheets("ScreenerOptions").Cells(14, 5).Value, _
**Operator:=xlTop10Percent**
End If
End If
End With
Worksheets("Master1").Activate
End Sub
但是,当我更改最后一个运算符以链接到单元而不是硬编码xlTop10Percent时:
Operator:=Worksheets("ScreenerOptions").Cells(14, 3).Value
我收到错误:
运行时'1004:Range类的自动筛选方法失败。
有人可以帮忙吗?如此接近完成!
字符串“ xlTop10Percent”只是一个字符串-VBA中没有机制直接将其转换为xlTop10Percent常量的值。
尽管您可以用数值(5)代替它,但这应该可以。
https://docs.microsoft.com/en-us/office/vba/api/excel.xlautofilteroperator
如果要在表中使用“友好的”名称,则可以在工作表上创建查找表以将其转换为数值。