VBA excel - 查找列并对其进行过滤

时间:2016-10-11 09:40:22

标签: excel vba excel-vba filter

我是VBA的新手,并试图自己学习一些工作目的。我一直在尝试创建一个宏,它会在我的工作表中找到一列,然后按特定的单词过滤它。通常我会在谷歌中找到代码然后编辑它们,但我遇到了这个问题..

我能找到的东西:

Sub sorting()

Dim col As String, cfind As Range

Worksheets(1).Activate

col = "Type"

Set cfind = Cells.Find(what:=col, lookat:=xlWhole)

ActiveSheet.Cells.Sort key1:=cfind, Header:=xlYes

End Sub

现在我尝试将“sort”部分更改为autofilter。但它根本不起作用..

.Range("A1:D1").AutoFilter Field:="col", Criteria1:="Virtual"
你可以帮忙吗? 谢谢! 椰油

1 个答案:

答案 0 :(得分:1)

Autofilter方法中,Field参数为“您想要基于过滤器的字段的整数偏移量(从列表的左侧开始;最左边的字段是字段之一)。“

编辑以在一些OP的澄清之后增强代码:

选项明确

Sub autofiltering()
    Dim col As String, cfind As Range

    col = "Type"
    With Worksheets("AF") '<-- reference your relevant worksheet (change "AF" to your actual worksheet name)
        With .Range("A1", .Cells(1, .Columns.Count).End(xlToLeft)) '<-- reference its row 1 cells from column 1 rightwards to last not empty one
            Set cfind = .Find(what:=col, LookIn:=xlValues, lookat:=xlWhole) '<-- look for the wanted column header
            If Not cfind Is Nothing Then '<-- if the header has been found
                .AutoFilter Field:=cfind.Column, Criteria1:="Virtual" '<-- filter all columns of the referenced row cells

                ' do your things
            End If
        End With
        .AutoFilterMode = False '<-- show all rows back and remove autofilter buttons
    End With