You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MS Access VBA中获取控件的Control Source属性值

获取Access控件的ControlSource属性(反向读取绑定数据源)

核心方法

你要的反向操作其实非常直接——ControlSource属性本身是可读可写的,直接读取该属性就能拿到设计视图里设置的绑定字段或表达式,不需要找什么隐藏API或者特殊方法。

代码示例

1. 读取单个控件的ControlSource

比如你要获取Forms!Customers!AddressPart的绑定源,直接写:

Dim ctrl As Control
Set ctrl = Forms!Customers!AddressPart

' 读取ControlSource值
Dim controlSource As String
controlSource = ctrl.ControlSource

' 输出到立即窗口验证
Debug.Print controlSource ' 会输出"City"(对应你示例里的赋值)

2. 通用备注字段弹窗编辑器实现

下面是一个通用过程,传入目标控件后自动读取绑定的备注字段,弹出带滚动条的编辑窗口:

Sub ShowMemoEditor(targetCtrl As Control)
    Dim memoValue As Variant
    Dim memoFieldName As String
    Dim rs As Recordset
    
    ' 获取控件的绑定源
    memoFieldName = targetCtrl.ControlSource
    
    ' 过滤非绑定控件或计算控件
    If memoFieldName = "" Or Left(memoFieldName, 1) = "=" Then
        MsgBox "该控件未绑定到备注字段", vbExclamation
        Exit Sub
    End If
    
    ' 定位到当前记录并读取备注值
    Set rs = targetCtrl.Form.RecordsetClone
    rs.Bookmark = targetCtrl.Form.Bookmark
    memoValue = rs(memoFieldName).Value
    
    ' 弹出多行输入框用于编辑
    memoValue = InputBox("编辑备注内容:", "备注编辑器", memoValue, , , , 255)
    
    ' 更新字段值(如果用户未取消输入)
    If Not IsNull(memoValue) Then
        rs.Edit
        rs(memoFieldName).Value = memoValue
        rs.Update
        targetCtrl.Form.Requery ' 刷新表单显示
    End If
    
    rs.Close
    Set rs = Nothing
End Sub

3. 调用方式(以控件双击事件为例)

在目标控件的OnDblClick事件中添加代码:

Private Sub AddressPart_DblClick(Cancel As Integer)
    ShowMemoEditor Me.AddressPart
End Sub

注意事项

  • 如果ControlSource是计算表达式(比如=Left([City],3)),代码会自动过滤这类情况,因为无法直接编辑原数据。
  • 确保目标绑定字段是备注类型(Memo),否则多行输入框的意义不大。
  • 针对连续表单/数据表,代码通过RecordsetClone和Bookmark能精准定位到当前点击的记录。

内容的提问来源于stack exchange,提问作者Ali Kayn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:29:56