我在Excel文件中有一列包含100行。我正在尝试使用按钮将此列导入ListBox。
问题是只有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, 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
答案 0 :(得分:2)
我将您的AscW(...
更改为oSheet.Range("B" & oSheet.Rows.Count).End(xlUp).Row
,
这样您就可以将所有列B添加到ListBox
(仍然要小心,因为你的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, 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