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

    Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Inserting items into a collection (VBA/Word; Excel/2003)

    Author
    Topic
    #456744

    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.

    Viewing 0 reply threads
    Author
    Replies
    • #1142358

      Say you have a collection named col. Try the following code:

      Dim varItem As Variant
      varItem = col.Item(8)
      col.Remove Index:=8
      col.Add Item:=varItem, Before:=5

      Instead of the last line, you can also use

      col.Add Item:=varItem, After:=4

      • #1142359

        Thank you Hans

        Do you see any pitfalls in abbreviating the code as shown below?

             colFolders.Add Item:=colFolders.Item(8), Before:=5
             colFolders.Remove Index:=9 ' 8 + 1 inserted item
        • #1142360

          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.

    Viewing 0 reply threads
    Reply To: Inserting items into a collection (VBA/Word; Excel/2003)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: