If you put a breakpoint on
cell = oSheet.Range(cell).Value
you will see that the value of
cell
is
Nothing
You need to make sure you actually have some data in that cell before attempting to add it to the ListBox e.g.
If Not cell Is Nothing Then ListBox1.Items.Add(cell)
[EDIT after follow up query]
I've looked at the code properly now and you appear to only load data from the spreadsheet if there is already information in the ListBox - see that
For
statement.
As I understand it you want all of the data from the spreadsheet
except for the last row.
Because you have used
CreateObject
for the excel application you don't have access to as many properties as you would by using (for example) interop.
I would just read everything from the sheet and exit when you hit a blank cell (as you have already in your code). Note that there is a "danger" of running off the end of the sheet ... but you shouldn't have that much data in a GUI so I'm not checking that
i
is greater than the maximum row number.
Something like this ...
While True
cell = "E" & Convert.ToString(i)
i += 1
cell = oSheet.Range(cell).Value
If Not cell Is Nothing Then
ListBox1.Items.Add(cell)
Else
Exit While
End If
End While
Once you have all of the data then just remove the last entry
ListBox1.Items.RemoveAt(ListBox1.Items.Count - 1)
NB - if you are going to use a Sorted ListBox then make sure you switch of the sorting
ListBox1.Sorted = False"
and switch sort back on only
after you have filled it and removed the last item
There are some great articles on CodeProject if you want to explore other ways of manipulating Excel with VB.Net