Trying to write a VBA function that will return the column number given the header cell string and the worksheet name but I get the Subscript out of range error. Here is the function:
Public Function namedColumnNo(heading As String, shtName As String) As Long
' Return the column number with named header text'
' on given worksheet.
Dim r As Range
Dim wks As Worksheet
Debug.Print shtName
'Exit Function
Set wks = Sheets(shtName)
wks.Range("1:1").Select
With wks
r = .Range("1:1").Find(heading, LookIn:=xlValue)
If r Is Nothing Then
namedColumnNo = -1
Else: namedColumnNo = r.Column
End If
End With
End Function
I am using this test sub to call the funtion:
Public Sub getCol()
Debug.Print "Find MidTemp on " & DataSht.RawDataSht
Debug.Print "Col " & namedColumnNo("MidTemp", DataSht.RawDataSht)
End Sub
I have a user defined type DataSht where I have variables to name worksheets e.g.
Public Type dataShtNames
HeaderSht As String
RawDataSht As String
ResultDataSht As String
End Type
Public DataSht As dataShtNames
With the Exit Function statement uncommented the variables resolve OK with the debug.print statements I get
Find MidTemp on RawData
RawData:MidTemp
Col 0
Leaving the function to run through the error occurs at
Set wks = Sheets(shtName)
If I replace the argument shtName with the actual sheet name as a string "RawData", then the error moves down to the line using the second argument heading
. If I substitute a the parameter with a string here the error persists.
Is there something I am missing here? Some help will be much appreciated.
r = .Range("1:1").Find(heading, LookIn:=xlValue)
is missing aSet
keyword. I'm surprised that isn't throwing error 91. – Mathieu GuindonThisWorkbook
, and whether the "headings" actually belong toListObject
(table) objects. If that is the case, there's a much, much simpler way to go about this. – Mathieu GuindonDataSht.
variables. However, I will take the advice and learn more about theListObject
as I'm all for simpler solutions. Thanks – NigelH