【问题标题】:Filter multiple columns in table过滤表中的多个列
【发布时间】:2019-01-28 17:41:00
【问题描述】:

我的代码过滤一列然后打印。

我需要根据两列进行过滤,然后打印。 IE。根据工程师姓名(第 1 列)和路线(第 2 列)进行过滤。现在,它会过滤工程师姓名(第 1 列)。

Option Explicit
Sub filterandprint()

    Dim TempWks As Worksheet
    Dim wks As Worksheet

    Dim myRng As Range
    Dim myCell As Range
                
    'change to match your worksheet name
    Set wks = Worksheets("Table")
        
    Set TempWks = Worksheets.Add      'creates temporary worksheet

    wks.AutoFilterMode = False 'remove the arrows

    'assumes headers only in row 1, columns(1) will be the number of the column you base your filtering
    'this copies the unique filtering and pastes it on a new temp worksheet
    wks.Columns(1).AdvancedFilter Action:=xlFilterCopy, _
      CopyToRange:=TempWks.Range("A1"), Unique:=True

    With TempWks
        Set myRng = .Range("a2", .Cells(.Rows.Count, "A").End(xlUp))
    End With

    'looping
    With wks
        For Each myCell In myRng.Cells
            .UsedRange.AutoFilter Field:=1, Criteria1:=myCell.Value
            '.UsedRange.AutoFilter Field:=2, Criteria1:=myCell.Value
            .PrintOut Preview:=True
        Next myCell
    End With

    Application.DisplayAlerts = False
    TempWks.Delete    'deletes temporary worksheet
    Application.DisplayAlerts = True

End Sub

【问题讨论】:

  • 尝试用wks.Range("A:B").AdvancedFilter替换wks.Columns(1).AdvancedFilter
  • 我确实尝试过,它会将前两列复制到临时工作表中,这很棒,但它仍然只根据第一列中的值进行过滤。
  • 对于其他寻找答案的人,将上面的循环部分编辑到下面,它起作用了:Dim iLoop As Integer 'looping With wks For iLoop = 2 To 65 .UsedRange.AutoFilter Field:=1, Criteria1:=TempWks.Cells(iLoop, 1).Value .UsedRange.AutoFilter Field:=2, Criteria1:=TempWks.Cells(iLoop, 2).Value .PrintOut Preview:=True Next iLoop End With Application.DisplayAlerts = False TempWks.Delete 'deletes temporary worksheet Application.DisplayAlerts = True End Sub
  • 您实际上可以为自己的问题添加答案。这对于未来的用户来说是首选,以便更轻松地找到解决问题的方法:)
  • 啊!谢谢 - 新手,感谢任何帮助!

标签: excel vba filtering multiple-columns


【解决方案1】:

对于其他正在寻找答案的人,将上面的循环部分编辑到下面并且它起作用了:

   ...

    Dim iLoop As Integer

    'looping
    With wks
        For iLoop = 2 To 65
            .UsedRange.AutoFilter Field:=1, Criteria1:=TempWks.Cells(iLoop, 1).Value
            .UsedRange.AutoFilter Field:=2, Criteria1:=TempWks.Cells(iLoop, 2).Value
            .PrintOut Preview:=True
        Next iLoop
    End With

    Application.DisplayAlerts = False
    TempWks.Delete    'deletes temporary worksheet
    Application.DisplayAlerts = True

End Sub

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 2020-01-20
    • 2022-01-06
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2018-07-08
    相关资源
    最近更新 更多