将列表框导出到Excel

时间:2015-12-17 12:48:58

标签: vb.net excel vba excel-vba listbox

我试图将3个列表框导出到excel文件中。 每个列表框必须导出到不同的单元格。

调试时没有错误。 但它没有工作,并使表格冻结。

这是我的代码

 Private Sub Button1_Click(sender As Object, e As EventArgs)  Handles  Button1.Click
    MsExcel = CreateObject("Excel.Application")

    MsExcel.Workbooks.Open("C:\Users\User\Desktop\11.xlsx")

    OffS = 0

    For Each oItem In ListBox1.Items

        MsExcel.Range("AB2").Offset(OffS, 0).Value = oItem

        OffS = OffS + 1

        For Each oItemm In ListBox2.Items

            MsExcel.Range("AC2").Offset(OffS, 0).Value = oItemm

            OffS = OffS + 1

            For Each oItemmm In ListBox3.Items

                MsExcel.Range("AD2").Offset(OffS, 0).Value = oItemmm

                OffS = OffS + 1

            Next oItemmm

        Next oItemm

    Next oItem

    MsExcel.Visible = True

End Sub

1 个答案:

答案 0 :(得分:1)

你需要取消嵌套循环!
在你的代码中,ListBox2的循环将对ListBox1中的每个项执行,对ListBox3最差!

小心,如果你嵌套循环,你需要不同的控件/索引(这里你有3个嵌套循环的相同变量)

Private Sub Button1_Click(sender As Object, e As EventArgs)  Handles  Button1.Click
MsExcel = CreateObject("Excel.Application")
MsExcel.Workbooks.Open ("C:\Users\User\Desktop\11.xlsx")

OffS = 0
For Each oItem In ListBox1.Items
    MsExcel.Range("AB2").Offset(OffS, 0).Value = oItem
    OffS = OffS + 1
Next oItem

OffS = 0
For Each oItemm In ListBox2.Items
    MsExcel.Range("AC2").Offset(OffS, 0).Value = oItemm
    OffS = OffS + 1
Next oItemm

OffS = 0
For Each oItemmm In ListBox3.Items
    MsExcel.Range("AD2").Offset(OffS, 0).Value = oItemmm
    OffS = OffS + 1
Next oItemmm

MsExcel.Visible = True
End Sub