如何使用变量在 Access 表单上引用字段?

Posted

技术标签:

【中文标题】如何使用变量在 Access 表单上引用字段?【英文标题】:How can a reference fields on an Access form using a variable? 【发布时间】:2013-12-09 17:39:57 【问题描述】:

我在一个名为 [P101] 到 [P110] 的 Access 2010 表单上有 20 个文本框,它引用源表中的字段 [P101] 到 [P110]。可能包含或不包含值,但如果不是,我不想看到它们。我在表中还有一个字段 [UsedFields],它计算了正在使用的字段数量。在 Form_Current 中,我可以设置以下代码,但有没有办法可以设置 FOR NEXT 循环以使用字段名称的变量? 当前代码(有效但非常笨拙)是:

If UsedFields > 0 then
   P101.Visible = True
Else
   P101.Visible = False
End If
If UsedFields > 1 then
   P102.Visible = True
Else
   P102.Visible = False
End If
.
.  
.
.
If UsedFields > 9 then
   P110.Visible = True
Else
   P110.Visible = False
End If

由于字段数设置为从 10 增加到 100,我想使用一个变量来保存 TextBox 名称,例如:

Private Sub Form_Current()
    Dim Ctrl As Control
    Dim CtrlName As String
    Dim Counter As Long

    For Counter = 1 To 10
        CtrlName = "P" & Counter
        Set Ctrl = CtrlName
    If Counter > Me.UsedFields Then
        Ctrl.Visible = False
    Else
        Ctrl.Visible = True
    End If
End Sub

这样的参考可能吗?

【问题讨论】:

【参考方案1】:

您可以使用字符串变量来引用表单的Controls 集合中的项目。

Dim Ctrl As Control
Dim CtrlName As String
Dim Counter As Long

For Counter = 1 To 10
    CtrlName = "P" & Counter
    Set Ctrl = Me.Controls(CtrlName)
    If Counter > Me.UsedFields Then
        Ctrl.Visible = False
    Else
        Ctrl.Visible = True
    End If
Next

顺便说一句,如果有意义的话,您可以使用一行来代替 If 块。

Ctrl.Visible = Not (Counter > Me.UsedFields)

【讨论】:

感谢 HansUp,它运行良好,节省了几百行代码。你是明星。

以上是关于如何使用变量在 Access 表单上引用字段?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 MS-Access 的表单上显示 Web 浏览器控件中的表格字段内容?

如何在 Microsoft Access 表单上计算年龄? [复制]

如何在 Access 2010 表单上显示“相关数据”

如何使用 Microsoft Access 导航表单过滤加载

当我引用其他表时,如何保存在 Access 2003 中的表单中创建的数据?

如何根据 Access 2013 中的另一个输入字段更新表单上的字段?