Excel VBA AutoFilter问题(字段值)

时间:2015-03-19 14:39:04

标签: excel vba excel-vba filter field

我无法找到解决我的代码问题的方法。

我们说我有这个记录集

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

自动过滤器应该在AR7列(第3列)中寻找ND,5

这些代码在AR代码不再具有后果之前效果很好。正如您在记录集中看到的那样,没有AR3,AR4,AR5和AR6列。因此,代码中的FilterField I对于AR1代码是1,对于AR2代码是2,而对于AR7代码则不是3(它的7)。因此代码返回错误'因为自动过滤范围中没有第7列。但真正的问题是即使该范围中有第7列,结果也会为零或错误,因为自动过滤器会搜索第7列而不是第3列。

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

如何修复代码才能使其正常工作?要使Autofilter在右栏中查找代码吗?

请注意,我无法在文件中添加假列以适应范围。

希望我能很好地解释自己......提前致谢


工作代码

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

1 个答案:

答案 0 :(得分:2)

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

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