1

I am getting some unexpected results from typename and am stumped. Hopefully some can point me in the right direction.

Private Sub T()
    Dim d As Word.Document
    Dim s As String
    Dim c As Collection
    Dim i As Long
    Dim o As Object

    Set d = ActiveDocument
    s = "X"
    Set c = New Collection

    Debug.Print "d is a " & TypeName(d)
    Debug.Print "s is a " & TypeName(s)
    Debug.Print "c is a " & TypeName(c)

    c.Add (d)
    c.Add (s)
    For i = 1 To c.count
        Debug.Print "Item " & i & " of the collection is a " & " " & TypeName(c.Item(i))
    Next i
End Sub

From which I get the following output:

d is a Document
s is a String
c is a Collection
Item 1 of the collection is a String
Item 2 of the collection is a String

What I expected to get was:

d is a Document
s is a String
c is a Collection
Item 1 of the collection is a Document
Item 2 of the collection is a String

Any ideas why I get "String" instead of "Document" for the first item in the collection?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user3117497
  • 13
  • 1
  • 5

1 Answers1

5
c.Add (d) 

is not the same as

c.Add d 

In the first, by wrapping d in parentheses you're causing it to be evaluated as an expression and the result of that expression (in this case a String) gets added to the collection. In the second, the d object itself is added.

Try comparing directly in the Immediate window:

? TypeName(ActiveDocument)       '>> Document

and

? TypeName( (ActiveDocument) )   '>> String
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
  • Thank you. I don't know if I ever would have figured that out. Couldn't even count how many times I head the help and kept coming up with the same thing every time. Thanks again. – user3117497 Mar 06 '14 at 00:59
  • 1
    No problem. One way to flag these types of issues is to watch out for when the VBEditor adds or preserves a space between a keyword (eg. a method name such as Add) and an opening parenthesis - if the parenthesis is required for the method call there will be no space there (and the editor will remove it if you put one...) – Tim Williams Mar 06 '14 at 01:03