创build一个自动filter代码

早上好,

我相当新的VBA,并寻求一些帮助编写我的表的自动filter代码。

Tariffs | SME100 | Enterprise | CustomerLoyalty | AccountManage ------------+-----------+---------------+-------------------+------------------- Voda Red | 1 | 1 | 0 | 1 Voda 1G D | 1 | 0 | 1 | 0 1* eligible to sell 0* not eligible sell 

我试图编写一个代码,从validation框(“B2”)中获取值,并自动过滤该销售渠道的特定列,以获得符合条件的关税。 我目前的代码是:

 Sub Filter() Dim strRange As String strRange = "B" Dim b As Integer b = "2" Range = ActiveSheet.Cells(2, 2).Address(False, False) If Range = True And Range = "SME100" Then ActiveSheet.ListObjects("TariffTable").Range.AutoFilter Field:=2, Criteria1:="1" If Range = True And Range = "Enterprise" Then ActiveSheet.ListObjects("TariffTable").Range.AutoFilter Field:=3, Criteria1:="1" If Range = True And Range = "CustomerLoyalty" Then ActiveSheet.ListObjects("TariffTable").Range.AutoFilter Field:=4, Criteria1:="1" If Range = True And Range = "AccountManagement" Then ActiveSheet.ListObjects("TariffTable").Range.AutoFilter Field:=5, Criteria1:="1" Else MsgBox ("No Sales Channel Selected") End If End Sub 

任何意见将不胜感激

我会以不同的方式来处理它:

 Sub Filter() Dim columnNumber, tableRow, tableColumn, tableWidth As Integer Dim tableName, columnName As String tableName = "Table1" columnName = ActiveSheet.range("B2").Value 'This clears the existing filter ActiveSheet.ListObjects(tableName).range.AutoFilter 'Assign some numbers we need to know about the table to check the headers tableRow = ActiveSheet.ListObjects(tableName).range.Row tableColumn = ActiveSheet.ListObjects(tableName).range.Column tableWidth = ActiveSheet.ListObjects(tableName).range.Columns.Count 'If a column title with the specified value does not exist VBA throws an error which we need to catch, this is one of the many reasons I dislike VBA :D On Error GoTo ErrorHandler 'Search through the table column header row to find the specified column and assign the number to columnNumber columnNumber = Application.WorksheetFunction.Match(columnName, range(Cells(tableRow, tableColumn), Cells(tableRow, tableColumn + tableWidth)), 0) 'Apply the filter "1" to the found columnNumber ActiveSheet.ListObjects(tableName).range.AutoFilter Field:=columnNumber, Criteria1:="1" 'Exit the sub otherwise the "error handling" will be provoked Exit Sub ErrorHandler: MsgBox columnName & " does not exist" End Sub 

编辑:另外,你应该阅读和理解sancho.s的答案。

我build议修改,检查等

  1. 您可能需要Range = ActiveSheet.Cells(2, 2).Text (或使用不同的名称,见下文)。 这可能是错误的根源。 另外,你的代码还有很多需要改进的地方。

  2. 使用Dim colstr as Stringcolstr = ...而不是Range = ...

  3. 确保TariffTable正确定义。

  4. AccountManagement应该阅读AccountManage

  5. 确保ActiveSheet引用您要使用的工作Sheet

  6. 查询If colstr = "Enterprise" Then而不是If colstr = True And colstr = "Enterprise" Then (已经使用一个改变的名字)。

  7. 你可以改进使用多个If s,例如,与Select Case ,甚至匹配colstr与包含标题的Range

PS:你没有发布你的代码的输出/错误。