VB.NET 2003 Early Binding Automation Code Example:
Code:
Option Explicit On
Option Strict On
'Add a reference to MS Excel xx.0 Object Library
'Import the Excel Primary Interop Assembly
Imports Microsoft.Office.Interop
Public Class Form1
Inherits System.Windows.Forms.Form
"Windows Form Designer generated code"
Private moApp As Excel.Application
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Declare and create a Workbook object
Dim oWB As Excel.Workbook = moApp.Workbooks.Add()
'Make it Visible to the user now that we are going to use it
moApp.Visible = True
'Extra code to follow option strict so we can access a cell.
Dim oSht As Excel.Worksheet = DirectCast(oWB.Sheets("Sheet1"), Excel.Worksheet)
Dim oRange As Excel.Range = CType(oSht.Cells(1, 1), Excel.Range)
'Write some text into Cell A1 on Sheet1
oRange.Value = "Meow!"
'Make sure our object variable is destroyed and released since its going out of scope
oRange = Nothing
oSht = Nothing
oWB = Nothing
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Create our generic unknown object variable and trap for Excel not installed
Try
moApp = DirectCast(CreateObject("Excel.Application"), Excel.Application)
'Keep it hidden from the user until we need to use it
moApp.Visible = False
Catch ex As Exception
MessageBox.Show(ex.Message, "VB/Office Guru™ Excel Early Binding VB.NET Automation FAQ", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing
'Check if Excel Application is still instanciated
If IsNothing(moApp) = False Then
'Check if our Excel instance has any opened workbooks in it
If moApp.Workbooks.Count > 0 Then
'Close all open workbooks not saving them
'Loop backwards so the index information will be relevant as they close
For i As Integer = moApp.Workbooks.Count To 1 Step -1
moApp.Workbooks.Item(i).Close(SaveChanges:=False)
Next
End If
'Close our Excel Application object
moApp.Quit()
End If
'Make sure its destroyed
moApp = Nothing
'Absolutely none of our Excel instances will be left running!
End Sub
End Class