VBA - Find a column with a specific header and find sum of all the rows in that column

后端 未结 1 997
太阳男子
太阳男子 2020-12-11 06:42

I have a large sheet. I have to set multiple filters in that sheet to columns headers in dynamic positions. Once the filters are set, I have to find the particular column in

相关标签:
1条回答
  • 2020-12-11 07:25

    Ensure that you fully qualify your objects and also put in a check whether .Find returns something or not. Here is an example.

    Let's say your worksheet looks like this

    enter image description here

    Now try this code

    Option Explicit
    
    Sub Sample()
        Dim ws As Worksheet
        Dim aCell As Range, Rng As Range
        Dim col As Long, lRow As Long
        Dim colName As String
    
        '~~> Change this to the relevant sheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
    
        With ws
            Set aCell = .Range("A8:DD8").Find(What:="Nov", LookIn:=xlValues, LookAt:=xlWhole, _
                        MatchCase:=False, SearchFormat:=False)
    
            '~~> If Found
            If Not aCell Is Nothing Then
                col = aCell.Column
                colName = Split(.Cells(, col).Address, "$")(1)
    
                lRow = .Range(colName & .Rows.Count).End(xlUp).Row
    
                '~~> This is your range
                Set Rng = .Range(colName & "8:" & colName & lRow)
    
                Debug.Print Rng.Address
            '~~> If not found
            Else
                MsgBox "Nov Not Found"
            End If
        End With
    End Sub
    

    Output

    enter image description here

    0 讨论(0)
提交回复
热议问题