user3850146
user3850146

Reputation: 97

Preview/Print MS Access Report from Visual Basic

I have an Visual Basic 2013 program which connects to a MS Access 2010 database. After the program calculates and writes values out to the DB, I need to print a report that is in the Access DB.

I have read through this: How To Automate Microsoft Access From Visual Basic .NET

I found similar questions such as this: Vb.Net preview report from access database but they do not use the DoCmd.OpenReport method.

The code I have now is as follows:

Imports Access = Microsoft.Office.Interop.Access

Public Class FrmReports

    Dim oAccess As Access.application

    Private Sub btnSumByPlan_Click(sender As Object, e As EventArgs) Handles btnSumByPlan.Click

        oAccess = CreateObject("Access.Application")
        oAccess.visible = True
        oAccess.opencurrentdatabase ("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\CLI_CRVM.accdb")

        oAccess.docmd.openreport(ReportName:="SumByPlan", View:=Access.AcView.acViewPreview)

    End Sub
End Class

This code compiles but gives me the following error when it runs:

An unhandled exception of type 'System.InvalidCastException' occurred in CLI CRVM.exe

Additional information: Unable to cast COM object of type 'Microsoft.Office.Interop.Access.ApplicationClass' to class ype 'CLI_CRVM.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.

Thanks in advance.

Upvotes: 2

Views: 5099

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123849

The argument to the OpenCurrentDatabase() method of an Access.Application object is just the location of the database file, not an OLEDB connection string. Your statement should be something more like

oAccess.OpenCurrentDatabase("C:\path\to\CLI_CRVM.accdb")

Also, I am unable to say for certain if |DataDirectory| is meaningful in that context, but I highly doubt it.

Upvotes: 1

Related Questions