首页 > 解决方案 > 将数据从列表框导出到新工作簿时需要运行时错误 424 对象

问题描述

我正在尝试将数据从列表框中导出到新工作表。它一直工作到今天,我不知道我是否做了什么而我看不到它。这是我的代码:

    Private Sub Boton_Exportar_Click()


    Dim objexcel As Object
    Dim NombreArchivo As String
    Dim i As Integer, Fila As Integer


    If MsgBox("Seguro que desea exportar en excel?", vbYesNo + vbQuestion) = vbYes Then

    Application.ScreenUpdating = False

      Set objexcel = Workbooks.Add
      objexcel.Activate
      NombreArchivo = ActiveWorkbook.Name

    'Asignar los datos del reporte
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(1, 1) = "Delayed Filter"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(1, 2) = Me.ComboBox1

    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 1) = "Vendor"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 2) = "PO Number"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 3) = "Order Date"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 4) = "Part Number"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 5) = "Quantity"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 6) = "UM"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 7) = "Promised Date"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 8) = "Due Date"
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(3, 9) = "Status"


    Fila = 4
    For i = 0 To Me.ListBox1.ListCount - 1

    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 1) = Me.ListBox1.List(i, 0)
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 2) = Me.ListBox1.List(i, 1)
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 3) = CDate(Me.ListBox1.List(i, 2))
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 4) = Me.ListBox1.List(i, 3)
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 5) = Format(Me.ListBox1.List(i, 4), "#,###.00")
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 6) = Me.ListBox1.List(i, 5)
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 7) = CDate(Me.ListBox1.List(i, 6))
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 8) = CDate(Me.ListBox1.List(i, 7))
    Application.Workbooks(NombreArchivo).Worksheets(1).Cells(Fila, 9) = Me.ListBox1.List(i, 8)

    Fila = Fila + 1
    Next

    MsgBox "Los datos han sido exportados", vbInformation

End If

End Sub

突出显示的行是“objexcel.Activate”

标签: excelvbalistboxruntime-errorexport-to-excel

解决方案


不知道为什么Activate- 语句失败,但根本没有必要。新创建的工作簿会自动激活,但甚至不需要激活它。该变量objExcel已设置为新工作簿,因此您可以使用它。我建议将其声明为Workbook(而不是对象),也应更改名称(但这取决于您)。

你可以使用类似的东西

Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add

newWorkbook.Worksheets(1).Cells(1, 1) = "Delayed Filter"
newWorkbook.Worksheets(1).Cells(1, 2) = Me.ComboBox1
...

或者

With newWorkbook.Worksheets(1)
    .Cells(1, 1) = "Delayed Filter"
    .Cells(1, 2) = Me.ComboBox1
    ...
End With

推荐阅读