Find column name of active cell within ListObject in Excel

Fir*_*017 1 excel vba

I have a table defined in Excel as a ListObject:

在此输入图像描述

In VbA, I can access rows and columns using ListObject("table1").ListRows or ListObject("table1").ListColumns

In one of my subs, I wan't to know the active cell's column name. And because the columns could be moved around, I want this to be dynamic.

For example, in the previous image, let's say I clicked on a cell of the third column. I'd like to have a function that tells me the column name associated with that cell in the current ListObject.

In this case it would return Line Desc.

I tried to use a spy to find an object path that would allow me to figure out the column name, but I couldn't find any.

Before I start building a function that will do just that, I wanted to make sure I didn't miss anything in VbA objects repository.

Any idea if there is a built-in way to find the active cell's column name?

Thanks

Note: If I run out of time and create a function, I will post it here.

EDIT Here's what I have found so far:

Function ColumnName(byVal Target as Range)
    If Sheets("Equipements").Listobjects("tMain").Active then
        ColumnName = ListObjects("tMain").HeaderRowRange.Cells(1, Target.Column).Value
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

Pat*_*icK 5

当 ListObject 不是从 A 列开始时,您的方法可能会出现问题。

缺点:仅限于表“tMain”,不能在任何其他表上使用。

您可以尝试此操作(如果目标超过 1 个单元格,则仅使用左上角的单元格):

Option Explicit

Function ColumnName(ByRef Target As Range) As String
    If Not Target.ListObject Is Nothing Then
        ColumnName = Intersect(Target.ListObject.HeaderRowRange, Target.EntireColumn).Value
    Else
        ColumnName = ""
    End If
End Function
Run Code Online (Sandbox Code Playgroud)