VBA excel-查找列并对其进行筛选

VBA excel-查找列并对其进行筛选,vba,excel,filter,Vba,Excel,Filter,我是VBA新手,为了一些工作,我试图自学。我一直在尝试创建一个宏,该宏将在我的工作表中找到一列,然后按特定的单词对其进行过滤。通常我会在谷歌上找到代码,然后编辑它们,但我在这方面遇到了麻烦 我能找到的是: Sub sorting() Dim col As String, cfind As Range Worksheets(1).Activate col = "Type" Set cfind = Cells.Find(what:=col, lookat:=xlWhole) ActiveS

我是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
现在我尝试将“排序”部分更改为自动筛选。但这根本不起作用

.Range("A1:D1").AutoFilter Field:="col", Criteria1:="Virtual"
你能帮忙吗? 谢谢 Coco

在方法中,
字段
参数是“要作为过滤器基础的字段的整数偏移量(从列表的左侧;最左侧的字段是字段1)。”

在一些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
子自动筛选()
Dim col作为字符串,cfind作为范围
col=“类型”

使用工作表(“AF”)“欢迎您。此外,假设列标题位于第1行,您可能希望仅限制第一行上的
Find()
调用
Set cfind=.Rows(1).Find(what:=col,LookIn:=xlValues,lookat:=xlother)
请参阅编辑的代码,我在其中添加了注释,可能有助于您完成此操作。关键是1)使用对象(工作表、范围)的引用(通过使用
WIth-End WIth
块),然后让其他操作通过使用点(
)后缀来引用对象;2)将范围限制在其所需的最小扩展范围内,以免出现性能问题(访问单元格非常耗时)看起来不错!但是,我不知道如何对发现的内容进行简单的选择:cfind.select似乎不起作用。。还有什么我必须添加的吗?
cfind.Select如果放在
后面,则必须工作如果不是cfind,则检查。什么“似乎不起作用”?现在起作用了,我把它放错地方了!:)非常感谢你的帮助!