Autofilter字段使用标题名称

时间:2018-04-12 16:50:11

标签: excel vba

我尝试使用自动过滤功能,但使用带有标题名称的字段" ID"而是列数。我尽我所能,我得到了这个错误消息"高级过滤器在迭代时失败,运行时错误1004"

我被困了两天。为你提供帮助

代码:

Sub AdataPreparation()
Dim WorkBk As Workbook, WorkSh As Worksheet, WrkTab As range, FilterRow As Variant
Set WorkBk = Workbooks.Open(Filename:="C:\Users\Documents\DataApplied.xlsm")
Set WorkSh = Sheets("sheet2") 
WorkSh.Activate 
Set WrkTab = range("A1").CurrentRegion 
WrkTab = ActiveRange
FilterRow = Application.Match("ID", WrkTab, 0)
Selection.AutoFilter Field:=FilterRow, Criteria1:="="
End Sub

2 个答案:

答案 0 :(得分:1)

问题可能在于没有为.Autofilter选择任何内容进行过滤。尝试将Selection替换为范围,或.UsedRange

您也不需要WrkTab,我认为它没有任何意义 - 我在这里使用.Find代替:

Sub AdataPreparation()
Dim WorkBk As Workbook, WorkSh As Worksheet, FilterRow As Variant

Set WorkBk = Workbooks.Open(Filename:="C:\Users\Documents\DataApplied.xlsm")
Set WorkSh = Sheets("sheet2")

WorkSh.Activate

FilterRow = Rows("1:1").Find(What:="ID", LookAt:=xlWhole).Column

WorkSh.UsedRange.AutoFilter Field:=FilterRow, Criteria1:="="
End Sub

我应该补充一点,您最好明确引用您的范围,而不是使用UsedRange

答案 1 :(得分:0)

这可能会对您有所帮助:

Sub Macro1()
    Set r = Range("A1").CurrentRegion
    r.AutoFilter
    kolumn = r.Find(what:="ID", after:=r(1)).Column
    r.AutoFilter Field:=kolumn, Criteria1:="="
End Sub