I would like a function to return the index of a column given the rowIndex and a Cell Value:
'Get index of column given a heading name
Function FindColumnIndex(name As String, rowNumber As Integer) As Integer
Dim index As Integer
index = 1
Dim found As Boolean
found = False
Do While found = False
If Cells(rowNumber, index).Value = name Then
FindColumnIndex = index
Exit Do
End If
index = index + 1
Loop
FindColumnIndex = index
End Function
I will then assign this to a value:
Dim colIndex As Integer
colIndex = FindColumnIndex("Physical or Virtual", 2)
Problem is this isn’t working – and I am sure my function is incorrect – Anyone know what I’m doing wrong?
One thing I spotted off the bat:
The variable passed to the function is named
rowNumber, notrow. Change that line to:edit:
One other thing to note is that your function never actually stops on its own. The only reason it ever ends is because it runs into an application defined error when trying to read column 16385 (because Excel is limited to 16384 columns*), which immediately kills the function, returning a
#VALUEerror.The following revision prevents that and returns a -1 if the requested column name is not found:
[ * Excel 2007 is thus limited, anyway. I have no idea if newer versions have larger limits or not.]