Consulting

Results 1 to 2 of 2

Thread: Duplicate names for same range

  1. #1
    VBAX Regular
    Joined
    Mar 2009
    Posts
    47
    Location

    Duplicate names for same range

    I am still trying to get a hang of named ranges in VBA.

    I was curious to find out what happens when the same range is assigned to two different names, and which one would the name property of the range refer to in that case. So I wrote this small piece of code-

    [vba]Names("name1").Delete
    Names("name2").Delete
    Set range1 = .Range(Cells(1, 1), Cells(2, 2))
    Set range2 = .Range(Cells(1, 1), Cells(2, 2))
    Names.Add Name:="name1", RefersTo:="=" & range1.Address
    Names.Add Name:="name2", RefersTo:="=" & range2.Address
    MsgBox range2.Name.Name[/vba]
    I initially assumed that "name2" would get displayed in the message box, but oddly enough, it displayed "name1". However it displays "name2" if I change range1 to refer to a different set of cells from range2.

    I see three possible scenarios.
    1. Two range variables referring to the same cells
    2. Two names referring to the same range variable
    3. Two names referring to two range variables as in 1.

    I didn't come across any documentation as to how VBA sets the name property for the range variables in each case. As in the above example, it seems to depend on if there is another named range pointing to the same group of cells.

    I do realize that this is more out of curiosity. In real programming I guess one should not create such multiple references, either at the range level, or at the name level.

  2. #2
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
    It will pick the one first sorted alphabetically.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •