Private Sub CmdOpenInsp1201_Click()
Dim xlApp As Excel.Application
Dim xlWkb As Excel.Workbook
Dim xlWks As Excel.Worksheet
Dim SQLCpt As String
Dim SQLLt As String
Dim rsCpt As DAO.Recordset
Dim rsLt As DAO.Recordset
SQLCpt = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.Position " & _
" FROM TblMembers " & _
" WHERE TblMembers.Position='Capt #1' "
SQLLt = " SELECT [FirstName] & "" "" & [LastName] AS FullName, TblMembers.Position " & _
" FROM TblMembers " & _
" WHERE TblMembers.Position='Lt #1' "
Set rsCpt = CurrentDb.OpenRecordset(SQLCpt, dbOpenSnapshot)
Set rsLt = CurrentDb.OpenRecordset(SQLLt, dbOpenSnapshot)
Set xlApp = New Excel.Application
Set xlWkb = xlApp.Workbooks.Open(CurrentProject.Path & "\Trk_Insp_1201_10_08_2016.xlsx")
Set xlWks = xlWkb.Sheets("Oct")
xlApp.Visible = True
With xlWks
Do While Not rsCpt.EOF
.Range("U42").Value = Nz(rsCpt!FullName, "")
rsCpt.MoveNext
Loop
End With
With xlWks
Do While Not rsLt.EOF
.Range("AA42").Value = Nz(rsLt!FullName, "")
rsLt.MoveNext
Loop
End With
SubExit:
On Error Resume Next
rsCpt.Close
rsLt.Close
Set rsCpt = Nothing
Set rsLt = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & "=" & Err.Description, vbCritical + vbOKOnly, "An error occured"
GoTo SubExit
End Sub
这可以按预期运行并运行,但我不确定错误处理。我需要在sub的末尾打开文件,但是我发布了rs,这需要吗?这是做这个子的正确方法。
你会采用不同的方式吗?
感谢迄今为止的所有帮助。
d
答案 0 :(得分:0)
这是一个不错的模式,但你忘记了On Error GoTo SubError
Private Sub CmdOpenInsp1201_Click()
On Error GoTo SubError
' Code
SubExit:
On Error Resume Next
rsCpt.Close
rsLt.Close
Set rsCpt = Nothing
Set rsLt = Nothing
On Error GoTo 0
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & "=" & Err.Description, vbCritical + vbOKOnly, "An error occured"
GoTo SubExit
End Sub
答案 1 :(得分:0)
我们在Thomas的回答中的讨论。令人惊讶的是(我总是在错误处理程序中使用Resume <Exit>
)GoTo SubExit
对我不起作用。见评论。
这是我的标准错误处理(在MZ-Tools中自动插入模板):
Public Sub TestErrorHandler()
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
On Error GoTo TestErrorHandler_Error
' Raise error
Set rs1 = CurrentDb.OpenRecordset("NonExistingTable")
' This line will not be reached
Set rs2 = CurrentDb.OpenRecordset("OtherTable")
TestErrorHandler_Exit:
' This prints "0" because "Resume" clears the Err object
Debug.Print Err.Number, Err.Description
' Only needed if something *can* go wrong in the "Exit" cleanup code
On Error Resume Next
' The following line surprisingly raises error 91 "Object variable not set"
' when "GoTo TestErrorHandler_Exit" is used in the error handler!
rs1.Close
rs2.Close
Set rs1 = Nothing
Set rs2 = Nothing
On Error GoTo 0
Exit Sub
TestErrorHandler_Error:
Debug.Print Err.Number, Err.Description
MsgBox "Error " & Err.Number & " in Modulex.TestErrorHandler:" & vbCrLf & _
Err.Description, vbExclamation, "Error"
' Finish error handling
Resume TestErrorHandler_Exit
' Don't use this
' GoTo TestErrorHandler_Exit
End Sub