2017-10-20 121 views
0

我正在使用下面的代碼來審計我的表單以進行更改。當我使用tbl_MBR上的ID字段「MBRID」時,它可以很好地工作。但是,當我使用tbl_ItemMaster上的ID字段「IMID」時,出現錯誤:無法找到表達式中引用的字段「IMID」。任何想法爲什麼IMID無法找到?我的審計跟蹤腳本不工作

Private Sub Form_AfterDelConfirm(Status As Integer) 
If Status = acDeleteOK Then Call AuditChanges("IMID", "DELETE") 
End Sub 

Private Sub Form_BeforeUpdate(Cancel As Integer) 
If Me.NewRecord Then 
    Call AuditChanges("IMID", "NEW") 
Else 
    Call AuditChanges("IMID", "EDIT") 
End If 
End Sub 

Sub AuditChanges(IDField As String, UserAction As String) 
On Error GoTo AuditChanges_Err 
Dim cnn As ADODB.Connection 
Dim rst As ADODB.Recordset 
Dim ctl As Control 
Dim datTimeCheck As Date 
Dim strUserID As String 
Set cnn = CurrentProject.Connection 
Set rst = New ADODB.Recordset 
rst.Open "SELECT * FROM tbl_AuditChanges", cnn, adOpenDynamic, adLockOptimistic 
datTimeCheck = Now() 
strUserID = Environ("USERNAME") 
Select Case UserAction 
    Case "EDIT" 
     For Each ctl In Me.Controls 
     Debug.Print ctl.Name 
      If ctl.Tag = "Audit" Then 
       If Nz(ctl.Value) <> Nz(ctl.OldValue) Then 
        With rst 
         .AddNew 
         ![DateTime] = datTimeCheck 
         ![UserName] = strUserID 
         ![FormName] = Screen.ActiveForm.Name 
         ![Action] = UserAction 
         ![RecordID] = Screen.ActiveForm.Controls(IDField).Value 
         ![FieldName] = ctl.ControlSource 
         ![OldValue] = ctl.OldValue 
         ![NewValue] = ctl.Value 
         .Update 
        End With 
       End If 
      End If 
     Next ctl 
    Case Else 
     With rst 
      .AddNew 
      ![DateTime] = datTimeCheck 
      ![UserName] = strUserID 
      ![FormName] = Screen.ActiveForm.Name 
      ![Action] = UserAction 
      ![RecordID] = Screen.ActiveForm.Controls(IDField).Value 
      .Update 
     End With 
End Select 
AuditChanges_Exit: 
On Error Resume Next 
rst.Close 
cnn.Close 
Set rst = Nothing 
Set cnn = Nothing 
Exit Sub 
AuditChanges_Err: 
MsgBox Err.Description, vbCritical, "ERROR!" 
Resume AuditChanges_Exit 
End Sub 
+0

哪一行會引發錯誤?禁用錯誤處理程序進行調試。或者在第一行代碼上設置斷點並執行步驟。代碼正在尋找名爲IMID的控件。有一個嗎?控件不必與其綁定的字段命名相同。 – June7

+0

它不會給我那個信息。當我嘗試編譯它時,不會拋出任何錯誤。我試着一行一行地查找IMID時出現錯誤。當我使用MBRiD(tbl_MBR的ID字段)時,所有ctls都可以工作。 – Lando

回答

0

答案有點隱藏,但我找到了。字段IMID不在與子窗體關聯的查詢中。因此,當代碼查找「IMID」時,找不到它。

將「IMID」添加到查詢可解決問題。