通过控件访问VBA循环显示字段值作为控件名称

时间:2016-05-23 23:17:10

标签: vba ms-access access-vba

我有一个循环遍历表单上所有控件的函数。如果标签显示“audit”,它会跟踪对该字段所做的更改。它一直运作到现在。现在,它抛出了“此类对象不支持操作”的错误。当我关闭错误处理并检查代码时,由于某种原因,它将实际字段VALUE作为控件名称输入。任何帮助将非常感谢。这是代码:

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 个答案:

答案 0 :(得分: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