Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

vba - Unexpected results from typename

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...