bod
bod

Reputation: 63

Adding items to listbox from excel

I have a column in an Excel file that contain 100 rows. I'm trying to import this column into a ListBox using a button.

The problem is that only 48 rows are importing from the Excel column.

Why aren't all the rows inside the column imported?

Here is my code (vb.net form):

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    Dim oExcel As Object = CreateObject("Excel.Application")
    Dim oBook As Object = oExcel.Workbooks.Open("C:\Users\User\Desktop\1.xlsx")
    Dim oSheet As Object = oBook.Worksheets(1)
    Dim i As Integer
    Dim cell As String
    For i = 0 To AscW(ListBox1.Items.Count.ToString()(i = i + 1)) - 1
        'set cell name, e.g. A1, A2, etc
        cell = "B" & Convert.ToString(i + 1)
        ' get cell data from Excel
        cell = oSheet.Range(cell).Value
        If cell = "" Then
            Exit For
        Else
            ListBox5.Items.Add(cell)
        End If
    Next
    oExcel.Quit()
End Sub

Upvotes: 1

Views: 3281

Answers (1)

R3uK
R3uK

Reputation: 14537

I changed your AscW(... to oSheet.Range("B" & oSheet.Rows.Count).End(xlUp).Row,
so that you'll add all the column B to your ListBox

(still, be careful because of your Exit For you canNOT have an empty cell in the middle!)

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim oExcel As Object = CreateObject("Excel.Application")
    Dim oBook As Object = oExcel.Workbooks.Open("C:\Users\User\Desktop\1.xlsx")
    Dim oSheet As Object = oBook.Worksheets(1)
    Dim i As Integer
    Dim cell As String
For i = 0 To oSheet.Range("B" & oSheet.Rows.Count).End(xlUp).Row
    'set cell name, e.g. A1, A2, etc
    cell = "B" & Convert.ToString(i + 1)
    ' get cell data from Excel
    cell = oSheet.Range(cell).Value
    If cell = "" Then
        Exit For
    Else
        ListBox5.Items.Add (cell)
    End If
Next i
oExcel.Quit()
End Sub

Upvotes: 2

Related Questions