Can't instantiate a COM object written in C# from VBA (VB6 ok)

纵饮孤独 提交于 2019-11-28 08:33:16

I'm going to answer my own question, hopefully to spare others the hours of tedious drudgery I have just endured.

If you get this, it is because the .NET based COM assembly can't find the .NET framework

The solution is simple. Create a file containing the following

<?xml version="1.0"?>
<configuration>
  <startup>
   <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

Call it "Excel.Exe.Config" and place it in the same directory as "EXCEL.EXE"

Problem solved!

RC1, I tested this with your code from VBScript and from within Office 2007's Excel, everything works fine.

Since your able to create the COM object from within a VB6 form we should assume that your .net framework is ok. Can you rule out issues with VBA? Can you create a .vbs file and put this in it:

Dim o As Object  
Set o = CreateObject("Test9.COMINT")  
o.Init "A", "B"

Save the file and double click it. If you get an error, then I would think there is an issue with it being registered, if you don't get an error, then I would look at Office and VBA and see if something is missing or not installed properly.

Another option is to add a reference to COM object and use early binding? I think you might need to export a typelibrary first, but you should be able to add a reference and simple new the object up.

This works for me from VBA... I tried it using Word & Excel 2003 (SP3).

I'm not sure what you mean by "production" machine. Because this is a "client" application and must be executed on the client using Excel.

If you're automating Excel on the server and triggering this "interop" through a VBA call, you're asking for trouble :)

Assuming that by production, you mean the client machine where user will be using the Excel template / doc, these are the following pointers:

  1. Make sure you have the appropriate .Net framework
  2. That you have latest service packs for Office
  3. Try ascertain if this is a rights issue.

If you're feeling adventuristic, you could use a process explorer [from Microsoft sysinternals site] to see what're the DLLs loaded and where exactly are you getting the error and compare it to the list on your dev box.

Hope this helps.

rc1 is correct in that this is a .net error, thrown when Office can't decide which version of the Framework to use. However, Office isn't throwing a wobbly simply because it's spoilt for choice. There is a bug in how Office 2003 interacts with .net 2.0.

Installing the fix from Microsoft (KB908002) is a more flexible way of solving the problem than by forcing Excel to run in a particular version of .net.

See also: http://www.biopdf.com/guide/trouble_shoot_microsoft_office_2003.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!