Avoiding the Error "invalid reference to the property CurrentRecord"
There are several properties in the Access object model that raise errors in certain circumstances where there is no way you can test for that error condition ahead of time. To deal with these situations, I like to use "convenience functions."
Convenience Functions
Convenience functions are nothing more than 1-3 line functions that make the calling code more readable.
In situations where errors are unavoidable, they also make the calling code safer by isolating the disabled error handling.
Form.CurrentRecord: PROBLEM
The form object's CurrentRecord property "corresponds to the value shown in the record number box found in the lower-left corner of the form."
There are certain instances where calling this property results in error number 2455, "You entered an expression that has an invalid reference to the property CurrentRecord." I honestly can't remember which situations generate this error. It's been years since I've had to worry about it.
GetCurrentRecord: SOLUTION
The very simple solution is to wrap the call to the .CurrentRecord property inside of a function call. The first line of the function disables error handling (On Error Resume Next
).
If the call to the .CurrentRecord property raises an error, the function returns zero. This is an easy condition to test for and it avoids having to use custom error handling to deal with error 2455 in the calling code.
'---------------------------------------------------------------------------------------
' Procedure : GetCurrentRecord
' Author : Mike Wolfe
' Purpose : Convenience function meant to deal primarily with Error 2455: "You entered
' an expression that has an invalid reference to the property CurrentRecord."
' Notes - Always returns 0 if there is no current record, otherwise "The value
' specified by this property corresponds to the value shown in the record
' number box found in the lower-left corner of the form."
'---------------------------------------------------------------------------------------
Private Function GetCurrentRecord(Frm As Form) As Long
On Error Resume Next
GetCurrentRecord = Frm.CurrentRecord
End Function
Image by Rahul Yadav from Pixabay