I have a function in Excel VBA that searches for headers and uses them to define certain ranges. It looks like it would work perfectly fine but when I call it, it breaks on this line: Set rngHeaders = Intersect(Worksheets(sheetName).UsedRange, Worksheets(sheetName).Rows(ROW_HEADERS)) and I am not sure why. It gives me a subscript out of range error. The sheetName variable is a string and the sheet Sheet8 (that I am passing into it) does exist. I have posted the entire function below in addition to the line where I call it in the Sub. Any help would be greatly appreciated.
Function FindHeader(HEADER_NAME As String, sheetName As String) As Range
Dim rngHeaders As Range
Dim rngHdrFound As Range
Const ROW_HEADERS As Integer = 1
Set rngHeaders = Intersect(Worksheets(sheetName).UsedRange, Worksheets(sheetName).Rows(ROW_HEADERS))
Set rngHdrFound = rngHeaders.Find(HEADER_NAME)
If rngHdrFound Is Nothing Then
MsgBox ("ERROR: Cannot find appropriate header.")
Exit Function
End If
Set FindHeader = Range(rngHdrFound.Offset(1), rngHdrFound.End(xlDown))
End Function
Line that calls it:
Sheet8.Activate
sheetName = "Sheet8"
Set rng1 = FindHeader("Client Exclusion List", sheetName)
rngHdrFoundis defined.sheetName = "Sheet8"] line tosheetName = Sheet8.NameSet FindHeader...MsgBox Worksheets(sheetName).Namewhat happens?