Thursday, May 28, 2020

Get Column index based on column name using vba

Hi folks,

If you need to find the column index based on column name, when your column sequence is not fixed in your sheet, please find below code which might helpful to you.

Code sample 1:
 Set findrng = wST.Range("1:1")
 ColNameIndex = findrng.Find("searchcolname").Column

Code sample 2:
strnameindex = wST.Match("searchcolname",wST.Range("1:1"), 0)

Code sample 3:
Function GetHeaderColumn(shRead As Worksheet, header As String) As Integer
    Dim headers As Range
    Set headers = shRead.Range("1:1")
    GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function

Cheers.
TJ.

No comments:

Post a Comment