Excel VBA AutoFilter问题(字段值)

我无法find解决我的代码问题。

假设我有这个logging集

AR1 AR2 AR7 AR8 AR9 2015-02-28 Residential Pool ND,5 BDM IT0538700021972 2015-02-28 Residential Pool ND,5 BDM IT0538700021972 2015-02-28 Residential Pool ND,5 BDM IT0538700021972 2015-02-28 Residential Pool ND,6 BDM IT0538700021972 

自动filter应该在AR7列中查找ND,5(这是第3列)

这是直到AR代码不再是结果的代码。 正如您在logging集中看到的那样,没有AR3,AR4,AR5和AR6列。 因此,代码中的FilterField I对于AR1代码是1,对于AR2代码是2,对于AR7代码是3(对7)。 所以代码返回一个错误,因为自动筛选范围中没有第7列。 但是真正的问题在于,即使在该范围内存在第7列,结果也将是零或错误,因为自动filter将在第7列而不是第3列进行search。

 Sub LookFor_ND5() '--------- Dim FilterField (the number of the column). ' ActiveCell.Value comes from another workbook and lets say ' in this case is AR7, so FilterField will be 7 (instead of 3) Dim FilterField As String FilterField = Replace(ActiveCell.Value, "AR", "") '--------- Dim Criteria1 (the ND_Code I have to search) ----------- Dim ND_Code As String ND_Code = "ND,5" '--------- Some code to get the right working path and file ----------- Dim currentFldr As String DirNames = Split(ActiveWorkbook.Path, "\") currentFldr = DirNames(UBound(DirNames)) PathString = Replace(currentFldr, "-", "") Dim fileName As String fileName = ActiveWorkbook.Path & "\Mutuiresidenziali_" & PathString & "_RES.xlsx" Set WB = Workbooks.Open(fileName) '--------- AutoFilter ----------- Rows("1:1").Select Selection.AutoFilter ActiveSheet.Range("$A$1:$E$6000").AutoFilter Field:=FilterField, Criteria1:=ND_Code End Sub 

我如何修复代码以使其工作? 为了使自动filter寻找右列的代码?

考虑到我不能添加假的列到文件来适应范围。

希望我解释清楚自己…在此先感谢


工作代码

 Sub LookFor_ND5() '--------- Dim FilterField (the number of the column). Dim FilterField As String FilterField = ActiveCell.Value 'AR7 '--------- Dim Criteria1 (the ND_Code I have to search) ----------- Dim ND_Code As String ND_Code = "ND,5" '--------- Some code to get the right working path and file ----------- Dim currentFldr As String DirNames = Split(ActiveWorkbook.Path, "\") currentFldr = DirNames(UBound(DirNames)) PathString = Replace(currentFldr, "-", "") Dim fileName As String fileName = ActiveWorkbook.Path & "\Mutuiresidenziali_" & PathString & "_RES.xlsx" Set WB = Workbooks.Open(fileName) '--------- AutoFilter ----------- Rows("1:1").Select Selection.AutoFilter ActiveSheet.Range("$A$1:$E$6000").AutoFilter Field:=Application.Match(FilterField, Rows(1), 0), Criteria1:=ND_Code End Sub 

您可以使用MATCH获取列位置:

 ActiveSheet.Range("$A$1:$E$6000").AutoFilter Field:=Application.Match("AR7", Activesheet.Rows(1), 0), Criteria1:=ND_Code