2016-05-23 61 views
0

我有一個循環遍歷表單上所有控件的函數。如果標籤顯示「審覈」,它會跟蹤對該字段所做的更改。到現在爲止工作得很好。現在,它拋出了「這種類型的對象不支持操作」的錯誤。當我關閉錯誤處理並檢查代碼時,出於某種原因,它將實際的字段VALUE輸入爲控件名稱。任何幫助將非常感激。代碼如下:通過控件訪問VBA循環顯示字段值作爲控件名稱

Dim rst As Recordset 
Dim ctl As Control 
Dim datTimeCheck As Date 
Dim strUserID As String 
Dim dbs As DAO.Database 
Dim strSQL As String 

Set dbs = CurrentDb 
strSQL = "SELECT * FROM ChangeLog" 
Set rst = dbs.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges) 

datTimeCheck = Now() 
strUserID = Environ("USERNAME") 
For Each ctl In Screen.ActiveForm.Controls 
    If ctl.Tag = "Audit" Then 
     If Nz(ctl.Value) <> Nz(ctl.OldValue) Then 
      With rst 
       .AddNew 
       ![ChangeTimeStamp] = datTimeCheck 
       ![UserId] = strUserID 
       ![FormName] = Screen.ActiveForm.Name 
       ![LeadID] = Lead 
       ![EstID] = Estimate 
       ![EOINumber] = Order 
       ![InstalID] = Install 
       ![FieldName] = ctl.ControlSource 
       ![FieldValueBeforeChange] = Nz(ctl.OldValue, "Blank") 
       ![FieldValueAfterChange] = Nz(ctl.Value, "Blank") 
       .Update 
      End With 
     End If 
    End If 
Next ctl 

回答

1

並非所有控件都具有ControlSource屬性,如命令按鈕,矩形和線條。只有文本框,複選框,組合框,列表框等數據驅動的對象才具有此屬性。因此,請考慮使用文本框ControlType來調節您的搜索。因此,循環遍歷所有表單控件的挑戰!

... 
For Each ctl In Me.Form.Controls 
    If ctl.ControlType = acTextBox And _ 
     ctl.Tag = "Audit" And _ 
     Nz(ctl.Value) <> Nz(ctl.OldValue) Then 
      With rst 
       .AddNew 
       ![ChangeTimeStamp] = datTimeCheck 
       ![UserId] = strUserID 
       ![FormName] = Screen.ActiveForm.Name 
       ![LeadID] = Lead 
       ![EstID] = Estimate 
       ![EOINumber] = Order 
       ![InstalID] = Install 
       ![FieldName] = ctl.ControlSource 
       ![FieldValueBeforeChange] = Nz(ctl.OldValue, "Blank") 
       ![FieldValueAfterChange] = Nz(ctl.Value, "Blank") 
       .Update 
      End With 
    End If 
Next ctl 
+0

我欣賞這個建議。我一定能夠使用它來提高效率。但是,這並不能解決問題。它仍然產生相同的錯誤。我有一個名爲「地址」的文本框,我測試的特定記錄上的值是「444 Shadow Hill」。當我運行代碼時,當我將它懸停在調試屏幕上時,它出錯並將ctl顯示爲「444 Shadow Hill」。 –

+0

調試器突出顯示哪一行?在'ctl.ControlSource'上? – Parfait

+0

關於「For Each ctl In Screen.ActiveForm.Controls」 –