如何 运行 ms 从 vb.net 访问宏?

How to run ms access macro from vb.net?

我正在尝试 运行 来自 vb.net 2010 的 ms access 2010 的宏 ..

我使用的代码是

Dim oAccess As Access.ApplicationClass

        'Start Access and open the database.
        oAccess = CreateObject("Access.Application")
        oAccess.Visible = True
        oAccess.OpenCurrentDatabase("C:\Users\Yuganshu\Desktop\New folder (4)\WindowsApplication1\db.mdb", False)

        'Run the macros.
        oAccess.Run("Macro1")
        'oAccess.Run("DoKbTestWithParameter", "Hello from VB .NET Client")

        'Clean-up: Quit Access without saving changes to the database.
        oAccess.DoCmd().Quit(Access.AcQuitOption.acQuitSaveNone)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oAccess)
        oAccess = Nothing

这给了我以下错误:

Unable to cast COM object of type 'Microsoft.Office.Interop.Access.ApplicationClass' to class type 'WindowsApplication1.Access.ApplicationClass'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

我不知道该怎么办。

您需要添加正确的 COM 引用。然后单击项目菜单栏-->添加引用。在类型库下查找 Microsoft Access 14.0 或您的计算机的任何版本 运行。然后添加以下语句。

Imports Microsoft.Office.Interop

Dim Access_Object As New Access.Application
Access_Object = CreateObject("Access.Application")
Access_Object.Application.Visible = True