VBA excel – find列并过滤它

我是VBA的新手,并试图自己学习一些工作目的。 我一直在试图创build一个macros,将在我的工作表中find一列,然后通过一个特定的词来过滤它。 通常我在谷歌find代码,只是编辑他们,但我有这个麻烦..

我能find什么:

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 

现在我试着改变“sorting”部分来自动过滤。 但它不工作..

 .Range("A1:D1").AutoFilter Field:="col", Criteria1:="Virtual" 

能否请你帮忙? 谢谢! cocoa

在Autofilter方法中, Field参数是“您希望基于filter的字段的整数偏移量(从列表的左侧;最左边的字段是字段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