如何在 Excel VBA 中使用 .NET 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/179452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make use of .NET objects from within Excel VBA?
提问by Matthew Murdoch
Can VBA code instantiate and use .NET objects? The specific class I'm interested in is System.IO.Compression.GZipStream.
VBA 代码可以实例化和使用 .NET 对象吗?我感兴趣的特定类是 System.IO.Compression.GZipStream。
For InfoGAC is the .NET Global Assembly Cache
信息GAC 是 .NET 全局程序集缓存
回答by Mike Rosenblum
I think Andy nailed this answer, but I'm not certain that the aspect regarding the CLR loading rules is exactly right.
我认为安迪确定了这个答案,但我不确定有关 CLR 加载规则的方面是否完全正确。
The .NET Assembly that holds the class acting as the wrapper for GZipStream would be exposed to COM and registered just like any other COM project library and class. In this regard, VBA would find the location of the COM-exposed .NET assembly via the registry. It might be smart to put the assembly in the GAC, so that it can't move (since moving the assembly would invalidate the registry info), but so long as the registry points to the right place, it should be fine.
包含充当 GZipStream 包装器的类的 .NET 程序集将向 COM 公开并注册,就像任何其他 COM 项目库和类一样。在这方面,VBA 将通过注册表找到暴露于 COM 的 .NET 程序集的位置。将程序集放在 GAC 中可能很聪明,这样它就不能移动(因为移动程序集会使注册表信息无效),但只要注册表指向正确的位置,就应该没问题。
A good beginner's tutorial on the subject is here
关于这个主题的一个很好的初学者教程在这里
Hope this helps...
希望这可以帮助...
回答by Andy
VBA can make use of any .NET objects that are exposed to COM. I don't know if GZipStream is or not, but I would guess that it would be easier for you to create a separate .NET object that is a wrapper around the functionality of GZipStream that you want to use. You can then expose your object to COM, and then VBA should make use of it.
VBA 可以使用任何公开给 COM 的 .NET 对象。我不知道 GZipStream 是否是,但我猜您创建一个单独的 .NET 对象会更容易,该对象是您想要使用的 GZipStream 功能的包装器。然后你可以将你的对象暴露给 COM,然后 VBA 应该使用它。
Note that the assembly containing your COM object (and its type library too, I think, although I'm not positive on that) need to either be in the same directory as the main executable (winword.exe, or whatever) or in the GAC. This is due to the CLR's loading rules for assemblies.
请注意,包含您的 COM 对象(以及它的类型库,我认为,尽管我对此并不肯定)的程序集需要与主可执行文件(winword.exe 或其他)位于同一目录中,或者位于海关总署。这是由于 CLR 的程序集加载规则所致。