My Blog

Opening an Excel File

In continuation from here

If you want to open an existing Excel file then we will not use .Add method. Instead we will use the .Open method. Double click on the “Open” button and paste the code given below. This is how your code will look when you want to open an Excel file.

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    '~~> Define your Excel Objects
    Dim xlApp As New Excel.Application
    Dim xlWorkBook As Excel.Workbook

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '~~> Add a New Workbook
        xlWorkBook = xlApp.Workbooks.Add

        '~~> Display Excel
        xlApp.Visible = True
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        '~~> Opens an existing Workbook. Change path and filename as applicable
        xlWorkBook = xlApp.Workbooks.Open("C:\TutorialSample.xlsx")

        '~~> Display Excel
        xlApp.Visible = True
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Me.Close()
    End Sub
End Class

Now when you run the project, your form will launch and when you click on “Open” button, Excel will launch and the relevant workbook will open.