In continuation from here…
We already covered here how to create the form, set references and place the required buttons. Now we will open an existing workbook.
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 from Button2_Click() 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.
On a separate note, if you do not want to hardcode the file name then you can also use the openFileDialog to choose the file as shown below.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim openFileDialog1 As New OpenFileDialog() '~~> Change the parameters for openFileDialog here openFileDialog1.InitialDirectory = "c:\" openFileDialog1.Filter = "Excel files (*.xls*)|*.xls*" openFileDialog1.Title = "Select Site Master to use" openFileDialog1.RestoreDirectory = True If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then Dim xlApp As New Excel.Application Dim xlWorkBook As Excel.Workbook With xlApp .Visible = True '~~> Open workbook xlWorkBook = .Workbooks.Open(openFileDialog1.FileName) End With End If End Sub