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)

これTLITypeLib Information、[プロジェクト]->[参照]にあります。

于 2012-06-20T18:37:11.870 に答える