VB.NET: Reading Specific Cell in Excel FIle

Good day everyone ^_^.  

In this post I'll show you how to reading excel file by VB.NET code. I have an example named karyawan.xlsx and I saved it on  D:\karyawan.xlsx.

Here is what it looks like:


What I want is to get value of B2 cell on sheet1 and show it with Messagebox. First we need to add excel reference on menu Project -> Add Reference...


Find and choose Microsoft.Office.Interop.Excel then click OK (choose version that appropriate with your environtment).


Let's make a simple UI, only a form with a button.

Code behind:

Imports Microsoft.Office.Interop
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
                ByVal As System.EventArgs) Handles Button1.Click
        Dim xlApp 
As Excel.Application
        
Dim xlWorkBook As Excel.Workbook
        
Dim xlWorkSheet As Excel.Worksheet

        xlApp = New Excel.ApplicationClass
        xlWorkBook = xlApp.Workbooks.Open("D:\karyawan.xlsx")
        xlWorkSheet = xlWorkBook.Worksheets("sheet1")
        'display the cells value B2
        MsgBox(xlWorkSheet.Cells(2, 2).value)
        xlWorkBook.Close()
        xlApp.Quit()
    End Sub
End Class


Lets run!!!

Post a Comment

0 Comments