Click here to Skip to main content
15,881,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone,

In simple terms I would like to use Vb.net to extract the values of a range of specified cells from an excel workbook and display those values onto a form. I have no problems opening or running the excel application/workbook; I can even read a single cell or multiple cells from the workbook and display that value onto my form; however I have to specify each individually.

My question is: how can I read and then display the values from a specific range of cells (i.e. "A1:A6") onto a form?

Thank you very much.

Below is the code I had written. I know it is incorrect, any help would be greatly appreciated.

'Import
Imports Excel = Microsoft.Office.Interop.Excel


VB
Dim xlApp As Application = New Application
        Dim xlWorkBook As Workbook = xlApp.Workbooks.Open("FileName")
        Dim xlSheet As Worksheet = xlWorkBook.ActiveSheet
        Dim myRange As Excel.Range
        Dim rCount As Integer
        Dim cCount As Integer
        Dim Obj1, Obj2, Obj3 As Object

        myRange = xlSheet.Range("A2:A6")

        For rCount = 1 To myRange.Rows.Count
            For cCount = 1 To myRange.Columns.Count
                Obj1 = CType(myRange.Cells, Excel.Range)
                Obj2 = CType(myRange.Cells, Excel.Range)
                Obj3 = CType(myRange.Cells, Excel.Range)
                displayLabel.Text = Obj1.value + Environment.NewLine +
                                    Obj2.value + Environment.NewLine +
                                    Obj3.value
            Next
        Next

        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlSheet)
Posted
Updated 18-Aug-15 3:47am
v2

1 solution

If you debug your code you will find that Obj1 contains all of the values in your range, not just a single cell.

I also prefer to use the StringBuilder class rather than concatenating strings (you will need Imports System.Text)

So potentially the easiest way to iterate through all of the cells would be
VB
Dim sb As StringBuilder = New StringBuilder("")
For Each c As Excel.Range In myRange.Cells
    sb.Append(c.Value2)
    sb.Append(Environment.NewLine)
Next
displayLabel.Text = sb.ToString()

Note this also works if your range spans across multiple columns e.g. if you had
myRange = xlSheet.Range("A2:B6")
you would get the values from
A2
B2
A3
B3 etc
 
Share this answer
 
Comments
Maciej Los 18-Aug-15 17:15pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900