Read and write Excel 2000 - 2003 file - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

Click here for Excel 2007

Requirements: a Form, 2 TextBoxes and a Button.

Then add "Microsoft Excel 12.0 Object Library" reference. To do that click on Project Menu -- Add Reference, then go to COM tab. Then scroll to Microsoft Excel 12.0 Object Library then click ok.

Then go to the code page and add the following declarations under the Public Class Form1:

Dim APP As New Excel.Application
Dim worksheet As Excel.Worksheet
Dim workbook As Excel.Workbook


To get value from Excel file to TextBox:

The following is Button1 Click Event:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
Handles Button1.Click
        
        workbook = APP.Workbooks.Open("your path\Test.xls")
       worksheet = workbook.Sheets.Item(1)

		'Read the value from Cell A1, B1
		
        TextBox1.Text = worksheet.Cells(1, 1).Value
       TextBox2.Text = worksheet.Cells(1, 2).Value
        APP.ActiveWorkbook.Close(False, "your path\Test.xls")
        APP.Quit()
End Sub

To wirte to excel sheet from a text box:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
 Handles Button1.Click
        workbook = APP.Workbooks.Open("C:\Documents and Settings\Jimmy!!\Desktop\Test.xls")
       worksheet = workbook.Sheets.Item(1)
       worksheet.Cells(1, 1).Value = TextBox1.Text
       worksheet.Cells(1, 2).Value = TextBox2.Text
       workbook.Close(SaveChanges:=True)
       APP.Quit()
End Sub


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.