Results 1 to 5 of 5
  1. #1
    Silver Lounger
    Join Date
    Jul 2001
    Location
    Ottawa, Ontario, Canada
    Posts
    1,609
    Thanks
    0
    Thanked 1 Time in 1 Post

    Inserting items into a collection (VBA/Word; Excel/2003)

    I have a collection of items and wish to move one of them. I cannot seem to get the command structured correctly. Let us say that I want to move Item(8) from its current position such that it will be located between the current items 4 and 5.

    A code example to achieve this would be greatly appreciated.

    T.I.A.
    Regards
    Don

  2. #2
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts

    Re: Inserting items into a collection (VBA/Word; Excel/2003)

    Say you have a collection named col. Try the following code:
    <code>
    Dim varItem As Variant
    varItem = col.Item(8)
    col.Remove Index:=8
    col.Add Item:=varItem, Before:=5
    </code>
    Instead of the last line, you can also use
    <code>
    col.Add Item:=varItem, After:=4</code>

  3. #3
    Silver Lounger
    Join Date
    Jul 2001
    Location
    Ottawa, Ontario, Canada
    Posts
    1,609
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: Inserting items into a collection (VBA/Word; Excel/2003)

    Thank you Hans

    Do you see any pitfalls in abbreviating the code as shown below?
    <pre> colFolders.Add Item:=colFolders.Item(8), Before:=5
    colFolders.Remove Index:=9 ' 8 + 1 inserted item</pre>

    Regards
    Don

  4. #4
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts

    Re: Inserting items into a collection (VBA/Word; Excel/2003)

    Not in itself, but adding the new item before removing the old one would be a problem if you also want to set the Key of the inserted item to that of the original item, since the Key must be unique - you can't have two items with the same Key.

  5. #5
    Silver Lounger
    Join Date
    Jul 2001
    Location
    Ottawa, Ontario, Canada
    Posts
    1,609
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: Inserting items into a collection (VBA/Word; Excel/2003)

    Thanks for the insight.
    Regards
    Don

Posting Permissions

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