简体   繁体   中英

VBA: How to filter using table headings

I've created a macro button named “MCO Projects” which when clicked will filter my spreadsheet to only filter active MCO projects (looks for “MCO” in the Product column H and Phase 2b and Phase 3 in Phase-Gate Phase column R). It works fine now. However, the issue I'm having is if were to add a column to the spreadsheet before column H "Field 8" or between column H "Field 8" and column R "Field 18" (anything before the product column and the Phase-Gate Phase) it will throw off the macro calculation. For example, if I were to add a new column after column “G” it would mess up the macro and the projects would not filter correctly.

The goal is when clicking the "MCO Projects" macro button to filter the table by Product(Header) to look for "MCO" (Currently Field "8"). And to filter the Phase-Gate Phase(Header)(Currently Field "18") to include both "Phase 3" and "Phase 2b". So does anyone know of a way for the macro to look specifically at the Product column? Regardless if a column were to be added or deleted? Any help/guidance that you can provide would be greatly appreciated.

VBA Code

Table Screenshot

As your table starts at column A you have a number of choices. For example, you can use ListColumns with index to return the column number for Product field in table. Repeat this logic for the other fields. If it didn't start at A you could use same principle with a subtraction for start column as adjustment.

table.ListColumns("Product").Index  '<== Gives your 8 for Field:=

You can also use Find on HeaderRowRange

Option Explicit
Public Sub Test()
    Dim table As ListObject, field1 As Range, fieldFilter1 As Long
    Set table = ActiveSheet.ListObjects("Capacity_Model")

    Set field1 = table.HeaderRowRange.Find("Product")
    If Not field1 Is Nothing Then
        fieldFilter1 = field1.Column
    End If
    Debug.Print table.ListColumns("Product").Index
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM