2011-07-29 27 views
1

我有一個子例程,當我單擊我的窗體上的按鈕時運行。問題是無論發生什麼,錯誤塊都會被執行,我不知道爲什麼。 Access VBA不太好,所以這可能是一個簡單的錯誤。訪問VBA塊時執行它不應該

這裏是我的子:

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" 

    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 
+1

我們到達ErrHandler時有什麼Err.Number?它真的是零嗎? –

+0

@Tiago Cardoso - 是的,它是0. – MAW74656

+0

@Tiago Cardoso - 我應該說它應該是0(當dlookup作品找到合適的匹配時),但我根本不應該收到消息框在這些情況下。 – MAW74656

回答

0

實際上看起來像一個邏輯錯誤。如果FindFirst語句不匹配,則該例程應該退出,而不是繼續。我在消息箱下面添加了'Exit Sub',現在我很好。

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 
+0

很高興知道!這聽起來是與標題更改塊有關的東西... –

1

這是一個奇怪的行爲,確實如此。

我建議你將VBA中的錯誤陷印行爲從'破壞未知錯誤'改爲'破解所有錯誤',看看是否還有其他問題會引發錯誤。

另一件要做的事情就是檢查問題的具體位置,即切片代碼。我的第一個建議是刪除標題更改行,並重新運行子檢查行爲是否仍然發生。

此外,請確保整個項目正在編譯。如果不是,VBA可以輕鬆呈現奇怪的行爲。

改變它,讓我們知道會發生什麼...我看不出任何明顯的代碼錯誤。