Access表单上的引用字段如何使用变量? [英] How can a reference fields on an Access form using a variable?

查看:490
本文介绍了Access表单上的引用字段如何使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 20 text boxes on an Access 2010 form called [P101] to [P110] which refers to fields [P101] to [P110] in the source table. The may contain a value or not, but if not I do not want to see them. I also have a field [UsedFields] in the table which has counted how many of the fields are in use. In Form_Current I can set the following code but is there a way I could set a FOR NEXT loop to use a variable for the Field Name? The current code (which works but is very clumsy) is:

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名称,例如:

As the number of fields is set to increase from 10 to 100 I would like to use a variable to hold the TextBox name, something like:

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

这样的参考可能吗?

推荐答案

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

You can use your string variable to refer to an item in the form's Controls collection.

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块.

BTW, you can use a single line in place of the If block if that makes sense.

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

这篇关于Access表单上的引用字段如何使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆