Depending on the application you are making, it is useful to consider a dictionary. They are especially useful when you want to check if something exists. Take this example:
Dim dictNames as Scripting.Dictionary Sub CheckRangeWithDictionary() Dim nm As Name 'Initially, check whether names dictionary has already been created If Not dictNames Is Nothing Then 'if so, dictNames is set to nothing Set dictNames = Nothing End If 'Set to new dictionary and set compare mode to text Set dictNames = New Scripting.Dictionary dictNames.CompareMode = TextCompare 'For each Named Range For Each nm In ThisWorkbook.Names 'Check if it refers to an existing cell (bad references point to "#REF!" errors) If Not (Strings.Right(nm.RefersTo, 5) = "#REF!") Then 'Only in that case, create a Dictionary entry 'The key will be the name of the range and the item will be the address, worksheet included dictNames(nm.Name) = nm.RefersTo End If Next 'You now have a dictionary of valid named ranges that can be checked End Sub
As part of the main procedure, all you have to do is do an existence check before using the range
Sub CopyRange_MyRange() CheckRangeWithDictionary If dictNames.exists("MyRange") then Sheets(1).Range("MyRange").Copy end if End Sub
When loading the dictionary may look a little longer, it is very fast for processing and searching. It also becomes much easier to check if there is any named range referencing a valid address without using error handlers in this simple application.
Note that when using names at the sheet level, rather than at the workbook level, more complex keys must be used to ensure uniqueness. From how the dictionary was created, if the key is repeated, the value of the element is overwritten. This can be avoided by using the same Exists method as the check in the key creation statement. If you need a good link on how to use dictionaries, use one .
Good luck
FCastro
source share