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

时间:2013-12-09 17:39:57

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

我在Access 2010表单上有20个文本框,名为[P101]到[P110],它引用源表中的字段[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 个答案:

答案 0 :(得分:4)

您可以使用字符串变量来引用表单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)
相关问题