0

我遇到了excel互操作的问题。基本上,我想要做的是从 .NET 调用具有复杂参数类型的 excel 工作簿中的宏。但是,在这样做时,我遇到了 Application 和 ApplicationClass 之间的一些差异,这让我有些头疼。

这是一些代码:

Dim complexType As New BigBadClass

Dim result As Boolean = importerClass.ExcelApplication.ComObject.GetType().InvokeMember("Run", _
            Reflection.BindingFlags.Default + Reflection.BindingFlags.InvokeMethod, Nothing, _
            importerClass.ExcelApplication.ComObject, _
            New Object() {"TheMacroName", AStringValue, ALongValue, complexType})

在 excel VBA 宏中,complexType 被映射到一个对象。

(有趣的旁注,我首先在 C# 中尝试了这个并不断收到 Type Mismatch 异常,这与 C# 代码之间的唯一区别是它传入了在 VB.NET 中创建的 complexType,而 C# 版本传入了在中创建的 complexType C#。出于某种我还没有弄清楚的原因(对象类型的某种细微差别?),C# 失败了,而 VB.NET 则有效)

无论如何,使用上面的代码片段。它仅在 ExcelApplication.ComObject 是 ApplicationClass 而不是 Application 接口时才有效。应用程序没有 GetType() 成员。而且由于它们是 COM 类,因此您不能强制转换它们。如果可能的话,我更喜欢使用 Application,因为我有另一部分可以使用 GetObject(..) 自动为用户加载打开的工作簿,并且在使用 ApplicationClass 时会中断(因为你不能再一次转换 COM 类,所以你只能转换GetObject(..) 到一个应用程序接口)。

有没有人遇到过这个问题?
有没有办法在 ApplicationClass 中使用 GetObject(..) 之类的东西?
或者一种在应用程序中使用 GetType() 的方法?或者可能是某种方式来转换 COM 对象?即:将 Application 转换为 ApplicationClass

希望我的解释足够清楚,并且代码说明了我在做什么。

4

1 回答 1

1

您应该对此感兴趣:

使用 VB.Net 运行宏

当我看到反射时,我就知道这不太正确。

仅供参考,我已在源代码上发布了可用的代码:

    Dim oExcel As Excel.ApplicationClass
    Dim oBook As Excel.WorkbookClass
    Dim oBooks As Excel.Workbooks

    'Start Excel and open the workbook.'
    oExcel = CreateObject("Excel.Application")
    oExcel.Visible = True
    oBooks = oExcel.Workbooks
    oBook = oBooks.Open("c:\book1.xls")

    'Run the macros.'
    oExcel.Run ("DoKbTest")
    oExcel.Run("DoKbTestWithParameter", "Hello from VB .NET Client")

    'Clean-up: Close the workbook and quit Excel.'
    oBook.Close (False)
    System.Runtime.InteropServices.Marshal.ReleaseComObject (oBook)
    oBook = Nothing
    System.Runtime.InteropServices.Marshal.ReleaseComObject (oBooks)
    oBooks = Nothing
    oExcel.Quit()
    System.Runtime.InteropServices.Marshal.ReleaseComObject (oExcel)
    oExcel = Nothing
于 2009-10-06T22:32:16.377 回答