从Excel中添加项目到列表框
我有一个Excel文件中包含100行的列。 我试图使用一个button导入列到列表框。
问题是只有48行是从Excel列导入的。
为什么没有导入列中的所有行?
这是我的代码(vb.net表单):
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, eg 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
我改变了你的AscW(...
到oSheet.Range("B" & oSheet.Rows.Count).End(xlUp).Row
,
以便您将所有列B添加到您的列表框
(仍然要小心,因为你的Exit For
你不能有一个空的细胞在中间!)
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, eg 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