Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a column number from a table using the =COLUMN function

Tags:

excel

vba

I have the following function in Excel that returns the column number of a table based on the column header. The table is called Config and the table column header is value. The below will return to me the column number in excel.

=COLUMN(Config[Value])-COLUMN(Config)+1

Could anybody let me know how this can be used in VBA? I was hoping i could use something like ...

Application.WorksheetFunction.Column

but it seems Column is not available for me to use.

Would anyone have any ideas on this? Any help would be greatly appreciated.

like image 667
Geminiflipflop Avatar asked Jan 19 '26 11:01

Geminiflipflop


2 Answers

Since you're using a table (ListObject), you can refer to a ListColumn by its header. If you need the column number, you can use ListColumn.Range.Column - something like this.

Option Explicit

Sub Test()
    Dim lc As ListColumn
    Dim col As Long

    Set lc = Sheets("Sheet1").ListObjects("Table1").ListColumns("Data1")
    col = lc.Range.Column
    Debug.Print col
End Sub
like image 142
BigBen Avatar answered Jan 21 '26 07:01

BigBen


I used a much simpler method:

=COLUMNS(X[[#Headers],[A]:[B]])

Where:
 X is the Table name
 A is the name of the 1st column 
 B is the name of the column you need.

This formula is dynamic

like image 32
SMan Avatar answered Jan 21 '26 07:01

SMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!