2

给定一个 clsPerson 类型的对象:

dim oP as New clsPerson
oP.FirstName = "Sam"

有没有办法询问变量oP并创建该类型的新对象?

4

1 回答 1

1

如果该类已正确注册到 COM(即来自 ActiveX dll 项目),则可以:

Option Explicit

Private Type Guid
  Data1 As Long
  Data2 As Integer
  Data3 As Integer
  Data4(0 To 7) As Byte
End Type

Private Const CLSCTX_INPROC_SERVER As Long = 1
Private Const IID_IUnknown As String = "{00000000-0000-0000-C000-000000000046}"

Private Declare Function CLSIDFromString Lib "ole32.dll" (ByVal lpsz As Long, ByRef pclsid As Guid) As Long
Private Declare Function IIDFromString Lib "ole32.dll" (ByVal lpsz As Long, ByRef lpiid As Guid) As Long
Private Declare Function CoCreateInstance Lib "ole32.dll" (ByRef rclsid As Guid, ByVal pUnkOuter As Long, ByVal dwClsContext As Long, ByRef riid As Guid, ByRef ppv As Object) As Long



Public Function GetAnotherInstanceOf(ByVal this As Object) As Object
  Static iunk As Guid
  If iunk.Data4(7) = 0 Then
    IIDFromString StrPtr(IID_IUnknown), iunk
  End If

  Dim ti As TLI.TypeInfo

  With New TLI.TLIApplication
    Set ti = .ClassInfoFromObject(this)
  End With

  Dim clsid As Guid
  CLSIDFromString StrPtr(ti.Guid), clsid

  CoCreateInstance clsid, 0, CLSCTX_INPROC_SERVER, iunk, GetAnotherInstanceOf
End Function

用法:

Dim s As New MSXML2.DOMDocument60

Dim clone As Object

MsgBox TypeName(clone)
Set clone = GetAnotherInstanceOf(s)
MsgBox TypeName(clone)

可在项目 -> 参考TLI中找到。TypeLib Information

于 2012-06-20T18:37:11.870 回答