【问题标题】:How can a reference fields on an Access form using a variable?如何使用变量在 Access 表单上引用字段?
【发布时间】: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

这样的参考可能吗?

【问题讨论】:

    标签: ms-access ms-access-2007 vba ms-access-2010


    【解决方案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,它运行良好,节省了几百行代码。你是明星。
    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多