循环通过Excel范围填充Combobox VB.Net

时间:2015-01-03 03:10:28

标签: vb.net excel loops combobox iteration

我有一个程序需要迭代一个非常大的ex​​cel范围,将两个范围组合成一个组合框值。我有以下代码来执行此操作,但它所做的只是迭代第一个值五次。如果我删除第一个FOR循环,那么它只返回第一个值并且永远不会完成。关于我可以做些什么来改进这些代码并使其正常工作的任何建议?

        Dim i As Integer
    If TenantBox.SelectedItem = "CNS" Then
        WFMBook.Workbooks.Open("C:\Schedule.xlsx")
        For i = 0 To 5 Step +1
            For Each CNSCell In WFMBook.Range("A3:A1441").Cells
                f = CNSCell.Value.ToString
            Next
            For Each tst In WFMBook.Range("B3:B1441").Cells
                l = tst.Value.ToString
            Next
            ComboBox1.Items.Add(f + " " + l)
            If (i = 5) Then
                Exit For
            End If
            Console.WriteLine(i)
        Next
    End If

1 个答案:

答案 0 :(得分:1)

试试这个,如果VBA是1,只需将x更改为1.

If TenantBox.SelectedItem = "CNS" Then
        WFMBook.Workbooks.Open("C:\XHSchedule.xlsx")
            Dim colCount = WFMBook.Range("A3:A8").Cells.Count
        For x = 1 To colCount Step +1
            For Each CNSCell In WFMBook.Range("A3:A8").Cells
                f = WFMBook.Range("A3:A8").Cells(x).Value.ToString
                l = WFMBook.Range("B3:B8").Cells(x).Value.ToString
            Next
            ComboBox1.Items.Add(f + " " + l)
        Next
                End If