如何在VBA中动态添加Checkbox-Buttons到userform

时间:2016-05-23 12:55:13

标签: vba excel-vba for-loop checkbox excel

我有一个用户表单,包含5个pdf版本的5个复选框按钮。 好吧,当用户调用userform时,userform初始化5个复选框按钮以选择其中一个。目前,代码非常静态,不太好。

这里的例子是:

If rs.EOF = False Then
  Do Until rs.EOF Or i = 5
     Select Case i
       Case Is = 0
         frmOne.Version5.Visible = True
         frmOne.Version5.Caption = rs!versNo & "#" & rs!versFrom
         frmOne.Version5.tag = rs!versNo & "_" & rs!FiD & ".pdf"
       Case Is = 1
         frmOne.Version4.Visible = True
         frmOne.Version4.Caption = rs!versNo & "#" & rs!versFrom
         frmOne.Version4.tag = rs!versNo & "_" & rs!FiD & ".pdf"
       Case Is = 2
         frmOne.Version3.Visible = True
         frmOne.Version3.Caption = rs!versNo & "#" & rs!versFrom
         frmOne.Version3.tag = rs!versNo & "_" & rs!FiD & ".pdf"
       Case Is = 3
         frmOne.Version2.Visible = True
         frmOne.Version2.Caption = rs!versNo & "#" & rs!versFrom
         frmOne.Version2.tag = rs!versNo & "_" & rs!FiD & ".pdf"
       Case Is = 4
         frmOne.Version1.Visible = True
         frmOne.Version1.Caption = rs!versNo & "#" & rs!versFrom
         frmOne.Version1.tag = rs!versNo & "_" & rs!FiD & ".pdf"
    End Select
    i = i + 1
    rs.MoveNext
  Loop
End If

我认为有很多代码。所以我的意图是像下面的例子那样定义它,但这不起作用:

If rs.EOF = False Then
    For i = 1 To 5
      With frmOne
         .Version & i &.Visible = True
         .Version & i &.Caption = rs!versNo & "#" & rs!versFrom
         .Version & i &.tag = rs!versNo & "_" & rs!FiD & ".pdf"
      End With
      rs.MoveNext
    Next i
End If

有没有人知道如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如下:

If rs.EOF = False Then
    For i = 1 To 5
        With frmOne.Controls("Version" & i) '<~~ use Controls collection of Userform object
           .Visible = True
           .Caption = rs!versNo & "#" & rs!versFrom
           .Tag = rs!versNo & "_" & rs!FiD & ".pdf"
        End With
        rs.MoveNext
    Next i
End If

答案 1 :(得分:1)

您可以使用名称

来引用()集合
Controls

要在运行时实际添加控件:

If rs.EOF = False Then
    For i = 1 To 5
      With frmOne.Controls("Version" & i)
         .Visible = True
         .Caption = rs!versNo & "#" & rs!versFrom
         .tag = rs!versNo & "_" & rs!FiD & ".pdf"
      End With
      rs.MoveNext
    Next i
End If