如何修改Access子报表中文本框的ControlSource属性?
Access报表修改ControlSource触发267错误的解决方法
问题背景
我有一个带预览子报表的Access窗体,打印、保存和邮件按钮停靠在窗体底部,滚动报表时保持可见:
- 窗体
Form_Load事件通过设置subReport.SourceObject属性加载选中的报表 - 报表
Report_Load子程序从语言配置表读取文本,动态设置控件内容:- 标签的
Caption直接赋值,无异常:rpt.Controls(rsContorlsTexts(0)).Caption = rsContorlsTexts(1) - 文本框因需要
CanGrow属性,设计时将ControlSource设为="txtTitle " & [Title],运行时通过代码替换为表中对应文本:With rpt .Controls(rsContorlsTexts(0)).ControlSource = Replace(.Controls(rsContorlsTexts(0)).ControlSource, rsContorlsTexts(0), rsContorlsTexts(1)) End With
- 标签的
错误现象
修改第一个文本框的ControlSource时触发267错误:你输入的表达式引用了一个已关闭或不存在的对象。即使直接给未绑定文本框赋值固定表达式也会报错:
.Controls(rsContorlsTexts(0)).ControlSource = "=""abc "" & [Title]"
直接打开报表无异常,标签的Caption设置也正常。
解决方法
1. 延迟修改时机到Report_Open事件
Report_Load触发时,报表控件的绑定逻辑已启动,此时修改ControlSource会打乱初始化流程。改用Report_Open事件修改:
Private Sub Report_Open(Cancel As Integer) Dim rpt As Report Set rpt = Me ' 读取语言配置表并替换文本框ControlSource With rpt .Controls(rsContorlsTexts(0)).ControlSource = Replace(.Controls(rsContorlsTexts(0)).ControlSource, rsContorlsTexts(0), rsContorlsTexts(1)) End With End Sub
2. 直接赋值文本框Value替代ControlSource绑定
绕开控件绑定逻辑,直接给文本框Value赋值,同时保留CanGrow属性:
' 在Report_Open或Report_Load中执行 rpt.Controls(rsContorlsTexts(0)).Value = rsContorlsTexts(1) & rpt!Title
3. 验证控件与数据源的有效性
添加调试语句确认控件存在性和字段合法性:
Debug.Print "控件是否存在:" & Not (rpt.Controls(rsContorlsTexts(0)) Is Nothing) Debug.Print "数据源包含Title字段:" & rpt.Recordset.Fields("Title").Name
排除控件名称拼写错误、字段不存在等基础问题。
内容的提问来源于stack exchange,提问作者bbProg
相关产品推荐
相关产品推荐

