Code Code - 2 months ago 32
Vb.net Question

Excel.Application error in Visual Studio Express (Visual Basic)

Using Excel 2010, Visual Studio Express 2013.

I have added the Reference Object Library in Visual Studio for Microsoft Excel 14.0

Imports Microsoft.Office.Core
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range

' Start Excel and get Application object.
oXL = CreateObject("Excel.Application")
oXL.Visible = True
End Sub
End Class


However it gives me the following error:


Type 'Excel.Application' is not defined.

Type 'Excel.Workbook' is not defined.

Type 'Excel.Worksheet' is not defined.

Type 'Excel.Range' is not defined.


If I am using a wrong reference library for the excel version, please show how I can go about adding the proper object library to the list.

Answer

You have imported the wrong namespace.

Change

Imports Microsoft.Office.Core

to

Imports Microsoft.Office.Interop

You will need to add a reference to Microsoft Excel 15.0 Object Library if you have not already (replace 15.0 with your version)

And instead of late binding, you can use the correct types

' using the fully-qualified class name as an example.
' Excel.Application would work just fine because Microsoft.Office.Interop is imported
Dim oXL As Microsoft.Office.Interop.Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range

' Start Excel and get Application object.
oXL = New Excel.Application()
' note that you have proper intellisense now because oXl is no longer just an Object.
oXl.Visible = True

Lastly, to properly clean up your Excel reference, since it's a COM object, put this in your code where you are finished with the objects (when closing the form for example). Do this for each COM object you create.

System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL)