Checking for the Existence of a Name

The following function can be used to check for the existence of a user-defined name, even a hidden one, but does not return the existence of Excel's reserved names. It's a handy addition to your arsenal of "programmer's useful code":

Function NameExists(FindName As String) As Boolean Dim Rng As Range Dim myName As String On Error Resume Next myName = ActiveWorkbook.Names(FindName).Name If Err.Number = 0 Then NameExists = True End Function

The preceding code is also an example of how to use errors to your advantage. If the name for which you are searching doesn't exist, an error message is generated. By adding the On Error Resume Next line at the beginning, you force the code to continue. Then you use the Err.Number to tell you whether you ran into an error. If you didn't, then Err.Number is zero, which means the name exists; else, you had an error and the name does not exist.

0 0

Post a comment