I have a subroutine that runs when I click a button on my form. The problem is that no matter what happens, the error block is executed, and I can't figure out why. I'm not very good with Access VBA, so it may be a simple error.
Here's my sub:
Public 开发者_JAVA百科Sub findRecord()
Dim rs As DAO.Recordset
Set rs = Me.[dbo_NCL_SimmonsCodes subform1].Form.Recordset
rs.FindFirst "NCL_ItemNum=""LSIM-" & Me.Text0 & """"
If rs.NoMatch Then
MsgBox "No match found. Please try again." & vbNewLine & vbNewLine & "If this is a new item, please click the Add Record button to add.", vbInformation, "No Match"
End If
On Error GoTo description_Error
Me.lblDescription.Caption = DLookup("Description", "dbo_AL_ItemUPCs", "ItemCode ='" & Me.Text0 & "'")
Exit_FindRecord:
Exit Sub
description_Error:
MsgBox "Error " & Err.Number & ": " & Err.Description & vbNewLine & vbNewLine, vbExclamation, "VBA Error " & Err.Number
Me.lblDescription.Caption = "Error."
Resume Exit_FindRecord
End Sub
That's an odd behavior, indeed.
I'd suggest you to change the Error Trapping behavior in VBA from 'Break on Unhanded Errors' to 'Break on All Errors' to see if there's anything else raising errors around.
Another thing to do to check specifically where the problem is, is slicing up the code. My first suggestion would be to remove the Caption change line and rerun the sub to check if the behavior is still happening.
Besides, make sure the whole project is compiling. If not, VBA can easily present strange behaviors.
Change it and let us know what happens... I can't see anything clearly wrong with the code.
Actually looks like a logic error. If the FindFirst statement has no match, it the routine should exit there, instead of continuing. I added 'Exit Sub' below that messagebox, and now I'm good.
Public Sub findRecord()
Dim rs As DAO.Recordset
Set rs = Me.[dbo_NCL_SimmonsCodes subform1].Form.Recordset
rs.FindFirst "NCL_ItemNum=""LSIM-" & Me.Text0 & """"
If rs.NoMatch Then
MsgBox "No match found. Please try again." & vbNewLine & vbNewLine & "If this is a new item, please click the Add Record button to add.", vbInformation, "No Match"
Me.lblDescription.Caption = "Error - No match."
Exit Sub
'^^Added^^'
End If
On Error GoTo description_Error
Me.lblDescription.Caption = DLookup("Description", "dbo_AL_ItemUPCs", "ItemCode ='" & Me.Text0 & "'")
Exit_FindRecord:
Exit Sub
description_Error:
MsgBox "Error " & Err.Number & ": " & Err.Description & vbNewLine & vbNewLine, vbExclamation, "VBA Error " & Err.Number
Me.lblDescription.Caption = "Error."
Resume Exit_FindRecord
End Sub
精彩评论