I have a function where I specify the field I want and the header row number and it returns the column. E.g. =findField("Region",1)
would return the column number containing the header "Region". This worked well until I encountered a report containing duplicate names in the header row. E.g. instead of 1st and last name it would have "Name" for both fields so I needed to specify the occurrence I wanted as in =findField("Name",1,2)
for the 2nd occurrence. I came up with a solution but it has 2 issues. The first is that if the field is in the first column it won't work properly. E.g. if columns A and B have "Name" then =findField("Name",1,1)
would return the second field instead of the first and =findField("Name",1,2)
would wrap around and return the 1st which is not what I want. The second issue is that it wraps around which I would prefer it not to do at all. What I came up with is as follows:
Function findField2(fieldName As String, Optional rowStart As Long = 0, Optional occurrence As Long = 1)
Dim Found As Range, lastRow As Long, count As Integer, myCol As Long
If rowStart = 0 Then rowStart = getHeaderRow()
myCol = 1
For count = 1 To occurrence
Set Found = Rows(rowStart).Find(what:=fieldName, LookIn:=xlValues, lookat:=xlWhole, After:=Cells(rowStart, myCol))
If Found Is Nothing Then
MsgBox "Error: Can't find '" & fieldName & "' in row " & rowStart
Exit Function
Else
myCol = Found.Column
End If
Next count
lastRow = Cells(Rows.count, Found.Column).End(xlUp).Row
findField2 = Found.Column
What do I need to do to allow for the field being in column A? Putting in 0 for myCol doesn't work. The initial finding function was based off https://www.mrexcel.com/forum/excel-questions/629346-vba-finding-text-row-1-return-column.html and I was tweaking it to suit my needs.
Thanks, Ben