【发布时间】:2016-11-21 14:16:54
【问题描述】:
谁能解释为什么我的代码不允许我将数据保存到 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 文件中。
【问题讨论】:
-
代码运行速度似乎比您的计算机打开文件的速度要快。看看这个:stackoverflow.com/questions/33817414/…
-
感谢您的回复,我尝试编写 Threading.Thread.Sleep(10000) 这是 10 秒,但似乎问题仍然存在
-
我尝试了您提供的代码,但仍然无法正常工作。仍然是 MsgBox 的答案,但是在窗口调用中看到一个 msgbox 很烦人
-
当您说您使用
MsgBox时,您是等待一段时间再单击“确定”还是立即单击?同样出于好奇,如果您加载空白工作簿会发生什么(这只是为了测试速度,因为空白工作簿会比满行的工作簿加载更快)。 -
试过了,还是不行。我希望我能尽快解决这个问题。顺便说一句,感谢您的回复。