VB6 打开Excel,程序容易闭退,请优化源代码:Function ReadMateria() As Boolean Dim xlRow As Integer, xlBook As New Excel.Workbook, xlSheet As New Excel.Worksheet, xlApp As New Excel.Application Set xlApp = CreateObject("Excel.Application") Set xlBook = xlApp.Workbooks.Open(ProcessPath.Text) Set xlSheet = xlBook.Worksheets("Material") For xlRow = 1 To 30 xlSheet.Cells(xlRow + 5, xlCol + 2) = "00" Next If Not xlBook Is Nothing Then xlBook.Close (True) Set xlBook = Nothing Set xlSheet = Nothing xlApp.Quit Set xlApp = Nothing End Function
时间: 2024-04-27 10:23:11 浏览: 137
以下是经过优化后的代码,可以避免程序崩溃:
Function ReadMateria() As Boolean
Dim xlBook As Excel.Workbook, xlSheet As Excel.Worksheet, xlApp As Excel.Application
On Error GoTo ErrHandler
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open(ProcessPath.Text)
Set xlSheet = xlBook.Worksheets("Material")
For xlRow = 1 To 30
xlSheet.Cells(xlRow + 5, xlCol + 2) = "00"
Next
xlBook.Close (True)
Set xlSheet = Nothing
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
ReadMateria = True
Exit Function
ErrHandler:
xlBook.Close (False)
Set xlSheet = Nothing
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
ReadMateria = False
End Function
主要优化措施包括:
1. 使用 Dim 声明变量时,只需要声明变量类型即可,不需要再使用 New 关键字。
2. 使用 On Error GoTo ErrHandler 语句,避免程序出现错误时直接崩溃。
3. 在 ErrHandler 中关闭 Excel 文件,并释放所有对象的引用。
4. 将函数的返回值设为 True 或 False,以便在程序中判断是否读取成功。
阅读全文