I am trying to write a function as follow:
Function getEntityCode(fileName As String) As Range
Dim entitySheet As Worksheet
Dim c As Range
Dim i As Integer
Dim valid As Boolean
Dim finalRow As Integer
Dim finalCol As Integer
Set entitySheet = Workbooks("OHUploads.xlsm").Worksheets("EntityCodes")
finalRow = entitySheet.Cells(Application.Rows.Count, 1).End(xlUp).Row
On Error GoTo ErrHandler:
With entitySheet
Set c = .Range(.Cells(1, 3), .Cells(1, finalCol))
End With
valid = False
ErrHandler:
Debug.Print Error(Err)
If valid = False Then
Set getEntityCode = entitySheet.Range(entitySheet.Cells(1, 3), entitySheet.Cells(1, finalCol))
Else
Set getEntityCode = c
End If
End Function
But no matter how do it, when the statement execute to Set c = .Range(.Cells(1, 3), .Cells(i, finalCol)) It alway end up in the errHandler, and it always shows:Application-defined or object-defined error
I thought I have explicitely defined everything, can't see where I have done wrong, can anyone help me with this please, thank you very much.
ErrHandlersegment. You may want to place a error-less execution method stop prior to theErrHandlersegment. And if needed, have theErrHandlersegment redirect to the closing segment. Alot of times you will see people annotate the error segment asErr_Methodand the exit segment asExit_Method, withMethodbeing the name of the method. Helps with readability and flow control.