除非首先显示MsgBox,否则数据不会保存到Excel文件

时间:2016-11-21 14:16:54

标签: excel vb.net msgbox

有人可以解释为什么我的代码不允许我将数据保存到Excel,除非我包含MsgBox吗?

这是我的代码:

Sub createreport()
        Try
            Dim XA As New Excel.Application
            Dim wb As Excel.Workbook
            Dim ws As Excel.Worksheet
            wb = XA.Workbooks.Open(dataDirectory + "employee_info\dtr_emp.xlsx", False, False, True)
            ws = wb.Worksheets("Sheet1")

            MsgBox("Test") '<---- THIS IS THE MSGBOX I WAS TALKING ABOUT

            For i As Integer = 0 To Me.EmployeeInfoDataGridView.Rows.Count - 1
                Dim DGV As DataGridViewRow = Me.EmployeeInfoDataGridView.Rows(i)
                ws.Cells(7 + i, 1) = DGV.Cells(0).Value
                ws.Cells(7 + i, 2) = DGV.Cells(1).Value
                ws.Cells(7 + i, 3) = DGV.Cells(2).Value
                ws.Cells(7 + i, 4) = DGV.Cells(3).Value
                ws.Cells(7 + i, 5) = DGV.Cells(4).Value
                ws.Cells(7 + i, 6) = DGV.Cells(5).Value
                ws.Cells(7 + i, 7) = DGV.Cells(6).Value
                ws.Cells(7 + i, 8) = DGV.Cells(7).Value
                ws.Cells(7 + i, 9) = DGV.Cells(8).Value
                ws.Cells(7 + i, 10) = DGV.Cells(9).Value
                ws.Cells(7 + i, 11) = DGV.Cells(10).Value
                ws.Cells(7 + i, 12) = DGV.Cells(12).Value
                ws.Cells(7 + i, 13) = DGV.Cells(14).Value
            Next
            XA.Visible = False

            wb.SaveAs(dataDirectory + "employee_info\temp_" + Form1.lbl_date.Text + ".xlsx")
            wb.Close(True)
            XA.Quit()
            wb = Nothing : ws = Nothing : XA = Nothing
            Try
                My.Computer.FileSystem.CopyFile("employee_info\temp_" + Form1.lbl_date.Text + ".xlsx", "employee_info\employee_infos.xlsx", True)
                My.Computer.FileSystem.DeleteFile("employee_info\temp_" + Form1.lbl_date.Text + ".xlsx", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        exit_excel_process.Show()
    End Sub

除非我将MsgBox代码放入。

,否则不会将数据保存到Excel文件中

1 个答案:

答案 0 :(得分:0)

由于Try不起作用,焦点将被赶出Catch。这样做似乎过于复杂。请参阅下面的代码示例。你可以解决这个问题吗?

const b: typeof(a) = decorate(a)