6

I have a table created from List of data. How to find the header text of each column

Table

When I select the activecell's header is high lighted to orange but I want to retrieve that value using visual basic. I am able to find excel sheet's address but I need table's column header

   Private Sub Worksheet_Change(ByVal Target As Excel.Range)
      MsgBox Target.Value 
      MsgBox ActiveCell.Address
   End Sub

4 Answers 4

5

This will return the column header, if the passed cell is in a table

Function TableHeader(cl As Range) As Variant
    Dim lst As ListObject
    Dim strHeading As String

    Set lst = cl.ListObject

    If Not lst Is Nothing Then
        TableHeader = lst.HeaderRowRange.Cells(1, cl.Column - lst.Range.Column + 1).Value
    Else
        TableHeader = ""
    End If
End Function
Sign up to request clarification or add additional context in comments.

Comments

2

I was online searching for a good way to find the header value of any given cell in the table and after a little brainstorming came up with this working solution that I thought I would share.

    Target.Offset(1 - Target.Row).Value

In the event that your headers aren't in row 1 then change the 1 to whatever row they happen to be in.

Comments

2
strCurrentColName = Cells(ActiveCell.ListObject.Range.Row, ActiveCell.Column).Value

Comments

1

If by column header you mean the cell in the first row in the same column that a change has been made then you can construct the header using Cells, ie

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    MsgBox Target.Value
    MsgBox ActiveCell.Address & vbNewLine & "Column header is " & Cells(1, Target.Column)
End Sub

If your header was in row 2 you would use Cells(2, ActiveCell.Column) etc

[Updated after comment below]

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim rng1 As Range
Set rng1 = Target.End(xlUp)
MsgBox "First value before a blank cell/top of sheet is " & rng1.Value
End Sub

4 Comments

+1Thanks it is what I want but if the table is at the center of sheet it would not work !!
If your table is continuous then you could use my updated code above to find the header
Thanks but my table is not continuous but the first solution works since I made my table to appear always on top ;) :D
No probs :) If there is a way to determine the top of the table then it can be easily adapted (ie find and use a certain word "Development Region" if it is always at the top left , use a range name to "mark" the top of table etc)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.