Search code examples
excelvbaoffset

VBA_Offset for Column with Header


I've a data where I applied filter to the column based on its header. Now I want to make some changes to filtered data i.e. visible cells in the same column. I've below mentioned code where filter has been applied to column with header "Query Type" & it's column letter is "E". Is it possible to put offset based on the column header instead of column letter? Because column gets changing everytime. In below example, how E2 or E can be replaced dynamically to accommodate column with header? I tried replacing "E" with FiltCol; however it is not working.

Sub Filter()

Dim FiltCol As Variant

FiltCol = Rows("1:1").Find(What:="Query Type", LookAt:=xlWhole).Column

ActiveSheet.UsedRange.AutoFilter Field:=FiltCol, Criteria1:="Rejected"

ActiveSheet.Range("E2", Range("E" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible).FormulaR1C1 = "Accepted"

End Sub

Solution

  • When you want to deal with column numbers, you can use the .Cells-property of the worksheet. Cells expects 2 parameters, row and column. The row is always a (long) number, the column can be specified as number or with the column character(s)

    The following terms are all the same:

    ActiveSheet.Range("D3")
    ActiveSheet.Cells(3, 4)       
    ActiveSheet.Cells(3, "D")
    

    Your code could look like

    Sub Filter()
        Dim FiltCol As Variant
    
        With ActiveSheet
            FiltCol = .Rows("1:1").Find(What:="Query Type", LookAt:=xlWhole).Column
            Dim lastRow As Long
            lastRow = .Cells(.Rows.Count, FiltCol).End(xlUp).row
            .UsedRange.AutoFilter Field:=FiltCol, Criteria1:="Rejected"
    
            Dim visibleCells As Range
            On Error Resume Next    ' Avoid runtime error if nothing is found
            Set visibleCells = .Range(.Cells(2, FiltCol), .Cells(lastRow, FiltCol)).SpecialCells(xlCellTypeVisible)
            On Error GoTo 0
            
            If Not visibleCells Is Nothing Then
                visibleCells.Value2 = "Accepted"
            End If
        End With
    End Sub