2011-11-09 28 views
0

我有一個COM對象(用C#.NET構建)我在VBA(Excel)中使用,它會很好地列舉COM對象的字段並自動引用它們。在.NET中,這可以通過反射來完成。有沒有辦法在VBA中做到這一點?VBA可以枚舉COM對象的方法或字段嗎?

所以,與其

Dim x As MyCOMObject 
Set x = New MyCOMObject 
x.f1 = 1 
x.f2 = 2 
x.f3 = 3 

更多的東西一樣:

Dim x As MyCOMObject 
Set x = New MyCOMObject 
For i = 0 to COMFieldCount(x) - 1 
    SetCOMField(x, GetCOMFieldName(i), i+1) 
Next i 
+1

使用反射我不會做這在C#。你有沒有想過做一個這樣做的功能? –

+0

你可能想看看這個問題:http://stackoverflow.com/questions/547903/self-inspection-of-vb6-udts – GTG

+0

@parapurarajkumar,你爲什麼不在C#中使用反射?我正在嘗試做一個這樣做的函數,因此是一個問題。 – Ben

回答

1

你可能會需要完善這個代碼位,但它確實大概你在找什麼。 首先,您需要添加對「Typelib信息」,TLBINF32.dll的引用。我不確定這是Windows的一部分,還是附帶了我安裝在我的機器上的衆多SDK,但它位於System32文件夾中。

我假設你正在設置一個COM對象的屬性,所以你將調用「屬性放置」函數來設置你的對象的值。您可能需要檢查這些屬性的數據類型,我沒有在我的代碼中進行任何數據類型轉換。

的代碼看起來是這樣的:

'Define the variables 
Dim tliApp As TLI.TLIApplication 
Dim typeinfo As TLI.typeinfo 
Dim interface As TLI.InterfaceInfo 
Dim member As TLI.MemberInfo 

'Initialize typelib reflector 
Set tliApp = New TLI.TLIApplication 
'Get the type information about myObject (the COM object you want to process) 
Set typeinfo = tliApp.ClassInfoFromObject(myObject) 

'Set all properties of all the object's interfaces 
For Each interface In typeinfo.Interfaces 
    For Each member In interface.Members 
     'If this is a "property put" function 
     If member.InvokeKind = INVOKE_PROPERTYPUT Then 
      'Invoke the mebmer and set someValue to it. 
      'Note that you'll probably want to check what datatype to use and do some more error checking 
      CallByName myObject, member.Name, VbLet, someValue 
     End If 
    Next 
Next 
+0

CallByName是一個我不知道的非常有用的例程。但是,枚舉不適用於我的對象,因爲所識別的接口只是IDispatch(QueryInterface,AddRef等)以及一些額外的內容。 ClassInfoFromObject在我的對象上檢索的兩個接口是_MyObjectType和_Object。第一個只是一個IDispatch接口。第二個也包含成員ToString,Equals,GetHashCode和GetType。此外,我想設置字段而不是屬性;在我的C#模塊中,我已經聲明瞭public double aDoubleField; – Ben