yuganshu soni
yuganshu soni

Reputation: 25

How to run ms access macro from vb.net?

I'm trying to run a macro from ms access 2010 from vb.net 2010 ..

The code I used is

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

This is giving me following error:

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.

I don't know what to do.

Upvotes: 0

Views: 3569

Answers (1)

Dammer15
Dammer15

Reputation: 190

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

Upvotes: 1

Related Questions