Excel VBA 自动筛选问题(字段值)

Excel VBA AutoFilter issue (field value)

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

假设我有这个记录集

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 对于 AR1 代码是 1,对于 AR2 代码是 2,但对于 AR7 代码不是 3(它是 7)。所以代码 returns 是一个错误,因为自动筛选范围中没有第 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:$E00").AutoFilter Field:=FilterField, Criteria1:=ND_Code

End Sub

如何修复代码以使其正常工作?要使自动过滤器在右栏中查找代码?

考虑到我无法在文件中添加假列以适应范围。

希望我解释得很好...提前致谢


工作代码

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:$E00").AutoFilter Field:=Application.Match(FilterField,
 Rows(1), 0), Criteria1:=ND_Code

End Sub

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

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