Excel VBA。我想选择一个列并对其应用过滤器。列不必每次都在同一个地方,因此需要通过名称字符串选择它

时间:2016-07-01 12:32:25

标签: excel vba excel-vba

通过记录MACRO生成以下代码,需要选择列并按列名称应用过滤器。

Sub Macro1()
'
' Macro1 Macro
'

'
    Selection.AutoFilter
    Selection.AutoFilter
    ActiveSheet.Range("Logged On").AutoFilter Field:=4, Operator:= _
        xlFilterValues, Criteria2:=Array(1, "4/28/2016")

End Sub

1 个答案:

答案 0 :(得分:1)

您可以遍历列'名称并设置过滤器。

Option Explicit
'Applies a Filter to all Columns named "ColumnName" on the worksheet "ws" with a criteria "criteria"    
Sub ApplyFilterTOColumn(columnName As String, ws As Worksheet, criteria As String)

Dim rng As Range
Dim cell As Range

Set rng = ws.Range(ws.Range("A1"), ws.Range("A1").End(xlToRight))
For Each cell In rng

    If cell.Value = columnName Then

        cell.AutoFilter cell.Column, Criteria1:=criteria, Operator:=xlFilterValues

    End If

Next cell

End Sub


Sub test()

Dim ws As Worksheet
Dim columnName As String

columnName = "Example"
Set ws = ThisWorkbook.Worksheets(1)
ApplyFilterToColumn columnName, ws, "b"

End Sub

在: Before

在: After