如何从 vb.net 运行 ms access 宏?

如何从 vb.net 运行 ms access 宏?

问题描述:

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

I'm trying to run a macro from ms access 2010 from vb.net 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

这给了我以下错误:

无法将Microsoft.Office.Interop.Access.ApplicationClass"类型的 COM 对象转换为WindowsApplication1.Access.ApplicationClass"类型.代表 COM 组件的类型实例不能转换为不代表 COM 组件的类型;但是,只要底层 COM 组件支持对接口 IID 的 QueryInterface 调用,它们就可以转换为接口.

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 或您的机器正在运行的任何版本.然后添加以下语句.

You need to add the correct COM Reference. Click the Project Menu bar then-->Add reference. Under Type Libraries look for Microsoft Access 14.0 or whatever version your machine is running. Then add the following statements.

Imports Microsoft.Office.Interop

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