如何使用控件源的名称从控件获取值?

时间:2017-09-14 12:15:14

标签: access-vba ms-access-2010

我正在尝试编写一些代码来审核通过表单进行的更改。我有一个功能可以做到这一点:

Function WriteChanges()

Dim f As Form
Dim c As Control
Dim user As String
Dim db As DAO.Database
Dim cnn As ADODB.Connection
Dim MySet As ADODB.Recordset
Dim tbld As TableDef
Dim recsource As String

Set f = Screen.ActiveForm
Set db = CurrentDb
Set cnn = CurrentProject.Connection
Set MySet = New ADODB.Recordset
recsource = f.RecordSource
Set tbld = db.TableDefs(recsource)

pri_key = fFindPrimaryKeyFields(tbld)
Debug.Print "pri_key: "; pri_key
user = Environ("username")


MySet.Open "Audit", cnn, adOpenDynamic, adLockOptimistic, adCmdTable

For Each c In f.Controls
    Select Case c.ControlType
        Case acTextBox, acComboBox, acListBox, acOptionGroup
            If c.Value <> c.OldValue Then
                With MySet
                    .AddNew
                        ![EditDate] = Now
                        ![user] = user
                        ![SourceTable] = f.RecordSource
                        ![SourceField] = c.ControlSource
                        ![BeforeValue] = c.OldValue
                        ![AfterValue] = c.Value
                    .update
                End With
            End If
    End Select
Next c

MySet.Close
Set MySet = Nothing
Set f = Nothing
Set db = Nothing

End Function

我在各种表单的更新前属性上使用此函数,并使用每个控件中值的更改的详细信息填充Audit表。我还需要从主键字段获取值以添加到Audit表。我可以使用以下代码来识别表单记录源中主键的名称:

Function fFindPrimaryKeyFields(tdf As TableDef) As String

Dim idx As Index

On Error GoTo HandleIt

For Each idx In tdf.Indexes
    If idx.Primary Then
        fFindPrimaryKeyFields = Replace(idx.Fields, "+", "")
        GoTo OutHere
    End If
Next idx

OutHere:
Set idx = Nothing
Exit Function

HandleIt:
Select Case Err
    Case 0
    Resume Next
    Case Else
    Beep
    MsgBox Err & " " & Err.Description, vbCritical + vbOKOnly, "Error"
    fFindPrimaryKeyFields = vbNullString
    Resume OutHere
End Select

End Function

如何使用此方法从控件(文本框)中获取具有已识别主键作为其控制源的值。

请原谅我代码中的任何愚蠢错误,因为我是相对新手。提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我不是100%确定你想要什么,但是如果你有这个字段的名字,你可以使用以下内容:

Dim primaryKeyValue As Variant
Dim primaryKeyColumnName As String
primaryKeyColumnName = fFindPrimaryKeyFields(TableDefs!MyTable)
Dim f as Form
'Get the form somehow

Dim c As Control
On Error GoTo NextC 'Escape errors because lots of controls don't have a control source
For Each c In f.Controls
    If c.ControlSource = primaryKeyColumnName Then
        primaryKeyValue = c.Value
    End If
NextC:
Next c
On Error GoTo 0

答案 1 :(得分:0)

如果主键列是表单记录源的一部分,您只需通过以下方式阅读:

Debug.Print "PK value: " & f(pri_key)

记录源的每一列都是运行时的表单属性,与是否存在具有相同名称的控件无关。

注意:如果您的表单基于连接多个表的查询,则整个构造将停止工作。