Consulting

Results 1 to 3 of 3

Thread: Adding to Collections

  1. #1

    Smile Adding to Collections

    Morning everyone.

    Can somebody please explain to me why the following code produces different results?
    Private Sub Test()Set fso = CreateObject("Scripting.FileSystemObject")
    Dim Coll as new Collection, objFile as File
    Set objFile = fso.GetFile(Insert filepath here)
    Coll.Add(objFile)
    Coll.Add objFile
    End Sub
    In the first collection entry, it is a string object, and in the second collection entry, it is a file object.

    Took me a few hours to realize what was going wrong, but can't figure out why the two lines should be added differently?

    Thanks

  2. #2
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,730
    Location
    http://dailydoseofexcel.com/archives...p-parentheses/


    When you put parentheses around an object, VBA evaluates that object and, absent a property, returns the default property. The first Add might error or might not work as expected

    Simple example ('TypeName' needs it's own parens)

    Option Explicit
    Private Sub Test()
        Dim fso As Object
        Set fso = CreateObject("Scripting.FileSystemObject")
        Dim Coll As New Collection, objFile As Object
        Set objFile = fso.GetFile("c:\users\daddy\desktop\test.txt")
        
        MsgBox TypeName((objFile))
        MsgBox TypeName(objFile)
        
    End Sub
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

  3. #3
    Thanks Paul, good to know these little things, that in the end can make a huge difference.

Tags for this Thread

Posting Permissions

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