Say I have a given set of column headers and I know only the column header name. I just want to retrieve the column name e.g I'm searching for the column name "Text" and it is located in cell A, then I want A as my result but its giving me 1. Can anyone help me out.
Here is my code
Sub searchHeader()
columnNamesRow = 1 ' or whichever row your names are in
nameToSearch = "Text" ' or whatever name you want to search for
columnToUse = 0
lastUsedColumn = Worksheets("Sheet1").Cells(1, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column
For col = 1 To lastUsedColumn
If Worksheets("Sheet1").Cells(columnNamesRow, col).Value = nameToSearch Then
columnToUse = col
End If
Next col
If columnToUse > 0 Then
' found the column you wanted, do your thing here using "columnToUse" as the column index
MsgBox columnToUse
End If
End Sub
the function @newguy pointed is the answer
anyhow it may help you to consider:
use
Find()
method ofRange
object instead of looping through cellsuse the core of that function for your specific needs
like follows:
to be used as follows:
Use the number of the column you've obtained, and the row that contains the headers: