簡體   English   中英

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列中查找ND,5(其中第三列)

這是在AR代碼不再重要之前有效的代碼。 正如您在記錄集中看到的那樣,沒有AR3,AR4,AR5和AR6列。 因此,代碼中我暗淡的FilterField對於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

如何修復代碼以使其正常工作? 要使自動篩選器在右列中查找代碼?

考慮到我不能將偽列添加到文件中以適應范圍。

希望我能很好地解釋自己...預先感謝


工作代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM