2016-10-11 74 views
1

我是VBA的新手,并尝试自学某些工作目的。我一直在试图创建一个宏,它会在我的工作表中找到一列,然后通过特定的词进行过滤。通常我发现谷歌代码,只是对其进行编辑,但我有麻烦与此一..VBA excel - 查找列并将其过滤

我能找到什么:

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" 

你能帮忙吗? 谢谢! 可可

回答

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 
+0

谢谢你啊!它的工作:) – Coco

+0

不客气。此外,假设列标题在第1行中,您可能只想在第一行上限制Find()调用Set cfind = .Rows(1).Find(what:= col,LookIn:= xlValues,lookat:= xlWhole)' – user3598756

+0

噢好主意!将做:) – Coco